2015-05-01 11 views
5

Ho uno script seguente per visitare una pagina web usando il driver Chrome selenio di Python.Come posso impostare il proxy con l'autenticazione nel driver web chrome selenio usando python

from selenium import webdriver 
USERNAME = 'usename' 
PASSWORD = 'pass' 
proxies = ["xxx.xxx.xxx.xxx"] 
proxy_tpl ='{0}:{1}' 
proxy = proxy_tpl.format(proxies[0],'xx') 
chrome_options = webdriver.ChromeOptions() 
chrome_options.add_argument('--proxy-server=%s' % proxy) 
chrome = webdriver.Chrome(chrome_options=chrome_options) 
chrome.get("http://{0}:{1}@whatismyipaddress.com".format(USERNAME, PASSWORD)) 
driver.close() 

Chrome ancora chiedendo nome utente e password quando provo a eseguire script. Come posso autenticare il server proxy dallo script?

risposta

19

Ispirato da questo questo solution in php, ho scritto un equivalente in pitone:

from selenium import webdriver 
from selenium.webdriver.chrome.options import Options 
import zipfile 

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: "XXX.XXX.XXX.XXX", 
      port: parseInt(XXXX) 
      }, 
      bypassList: ["foobar.com"] 
     } 
     }; 

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

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

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("path/to/chromedriver", chrome_options=co) 
driver.get("http://www.google.com.br") 

In background_js stringa, sostituire la XXX con le tue informazioni.

+0

Ciao, grazie per questo codice. ha funzionato. Sono bloccato in un altro posto. Sto cercando di accedere utilizzando l'autenticazione OAuth2.0 e lo sto facendo sul mio localhost, quindi ho impostato localhost nel mio redirect_uri. Ma a causa di questo browser proxy non è possibile accedere a localhost. Puoi suggerirmi di accedere allo stesso. –

+1

voglio chiedere se {urls: ["< all_urls >"]}, ha bisogno di qualsiasi modifica o funziona così com'è. questo non è chiaro per me. – b10n1k

+0

Per me, al momento, ha funzionato così com'è. – user3286105

Problemi correlati