2016-03-14 79 views
0

我试图使用代理服务器来启动Selenium Chrome驱动程序。到目前为止,我发现的唯一解决方案是使用Chrome的一种插件进行身份验证,但它不是很可靠,所以我想知道是否还有其他选择。Selenium和Python的代理服务器

以下是我现在用

manifest_json = """ 
    { 
    "version": "1.0.0", 
    "manifest_version": 2, 
    "name": "Chrome Proxy", 
    "permissions": [ 
    "proxy", 
    "tabs", 
    "unlimitedStorage", 
    "storage", 
    "<all_urls>", 
    "webRequest", 
    "webRequestBlocking" 
    ], 
    "background": { 
    "scripts": ["background.js"] 
    }, 
    "minimum_chrome_version":"22.0.0" 
    } 
    """ 

background_js = """ 
    var config = { 
    mode: "fixed_servers", 
    rules: { 
    singleProxy: { 
    scheme: "http", 
    host: "", 
    port: parseInt(6060) 
    }, 
    bypassList: ["foobar.com"] 
    } 
    }; 

    chrome.proxy.settings.set({value: config, scope: "regular"}, function() {}); 

    function callbackFn(details) { 
    return { 
    authCredentials: { 
    username: "", 
    password: "" 
    } 
    }; 
    } 

    chrome.webRequest.onAuthRequired.addListener(
    callbackFn, 
    {urls: ["<all_urls>"]}, 
    ['blocking'] 
    ); 
    """ 


pluginfile = 'proxy_auth_plugin.zip' 

with zipfile.ZipFile(pluginfile, 'w') as zp: 
    zp.writestr("manifest.json", manifest_json) 
    zp.writestr("background.js", background_js) 

co = Options() 
co.add_argument("--start-maximized") 
co.add_extension(pluginfile) 


driver = webdriver.Chrome(executable_path='/usr/local/bin/chromedriver') 

回答

0

我不认为插件是一个很好的解决方案,当然不是当有纯HTTP的解决方案,在所有浏览器,版本和操作系统上运行相同。

对于Browsermob,您可以使用此Python wrapper,该文件是用Java编写的非常有名的独立或嵌入式代理服务器。

code显示了如何使用headers() Python方法添加标头,而不需要POST到REST API。该测试在使用它some examples,如:

self.client = Client("localhost:9090") 
self.client.headers({'User-Agent': 'rubber ducks floating in a row'}) 
self.client.headers({'Authorization': 'Basic dXNlcjpwYXNz'}) # User 'user', password 'pass' 

更新:

只是为了澄清的webdriver和代理如何结合在一起的:

  • 首次启动代理服务器,并等待它准备好。您可以在外部执行该操作,并将主机:端口传递给WebDriver,或者将其嵌入到您的应用程序中,然后将WebDriver传递给proxy对象。
  • This example演示了使用Firefox配置文件和Chrome选项的第二种方法。
  • 或者,启动代理嵌入式,使用它来获得代表Selenium代理服务器的Proxy对象,然后将其添加到您的DesiredCapabilities对象中,然后按照this example的方式创建您的驱动程序。

从那时开始,代理侦听是自动的,您可以开始创建HAR文件。


或者,您可以看到使用Twisted的自定义Python代理服务器的this answer

我对Python中的Selenium代理有更长的回答here

+0

谢谢。哪一个是Python包装? – Christian

+0

对不起,我错过了链接。现在修复了答案。 https://github.com/AutomatedTester/browsermob-proxy-py –

+0

thx再次。因此,这是Chrome的代码,例如从'browsermobproxy import Server server = Server(“path/to/browsermob-proxy”) server.start() proxy = server.create_proxy()chrome_options = webdriver.ChromeOptions() chrome_options.add_argument(“ - proxy-server = {0}”.format(proxy.proxy)) browser = webdriver.Chrome(chrome_options = chrome_options)' – Christian