Python + Selenium + Firefox 如何使用需要auth的代理?

我的代码如下:

self.current_proxy = {}
 self.current_proxy['proxy'] = "proxy:1000"
profile = webdriver.FirefoxProfile()
if 'proxy' in self.current_proxy:
    proxy_arr = Common.ic_explode(self.current_proxy['proxy'], ":")
    profile.set_preference('network.proxy.type', 1)
    profile.set_preference('network.proxy.http', proxy_arr[0])
    profile.set_preference('network.proxy.http_port', int(proxy_arr[1]))
    profile.set_preference('network.proxy.ssl', proxy_arr[0])
    profile.set_preference('network.proxy.ssl_port', int(proxy_arr[1]))
    #profile.set_preference("network.proxy.user_name", 'aaaaa')
    #profile.set_preference("network.proxy.password", 'bbbbb')
profile.update_preferences()
self.browser = webdriver.Firefox(profile)
self.browser.set_page_load_timeout(100)
self.browser.implicitly_wait(5)
self.browser.get("http://www.baidu.com")

这两句是不起效果的

#profile.set_preference("network.proxy.user_name", 'aaaaa')
#profile.set_preference("network.proxy.password", 'bbbbb')

请教高手如何做?

阅读 6.6k
评论 2016-10-12 提问
    2 个回答

    算是解决了吧~ 附上自己的测试代码:(.xpi文件Google搜下都能搜到下载地址)

    from base64 import b64encode
    proxy = {
        "host": "proxy.com",
        "port": "1000",
        "user": "usr123",
        "pass": "pwd123"
    }
    profile = webdriver.FirefoxProfile()
    # add new header
    profile.add_extension("modify_headers-0.7.1.1-fx.xpi")
    profile.set_preference("extensions.modify_headers.currentVersion", "0.7.1.1-fx")
    profile.set_preference("modifyheaders.config.active", True)
    profile.set_preference("modifyheaders.headers.count", 1)
    profile.set_preference("modifyheaders.headers.action0", "Add")
    profile.set_preference("modifyheaders.headers.name0", "Proxy-Switch-Ip")
    profile.set_preference("modifyheaders.headers.value0", "yes")
    profile.set_preference("modifyheaders.headers.enabled0", True)
    
    # add proxy
    profile.set_preference('network.proxy.type', 1)
    profile.set_preference('network.proxy.http', proxy['host'])
    profile.set_preference('network.proxy.http_port', int(proxy['port']))
    profile.set_preference('network.proxy.no_proxies_on', 'localhost, 127.0.0.1')
    
    # Proxy auto login
    profile.add_extension('closeproxy.xpi')
    credentials = '{user}:{pass}'.format(**proxy)
    credentials = b64encode(credentials.encode('ascii')).decode('utf-8')
    profile.set_preference('extensions.closeproxyauth.authtoken', credentials)
    
    driver = webdriver.Firefox(profile)
    driver.get("http://1212.ip138.com/ic.asp")
    print driver.page_source
    driver.quit()
    评论 赞赏 2016-10-13