2016-03-14 78 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