2012-07-12 15 views
16

Estoy usando este código:¿Cómo se configura sustituto de cromo en Python WebDriver

profile = webdriver.FirefoxProfile() 
profile.set_preference("network.proxy.type", 1) 
profile.set_preference("network.proxy.http", "proxy.server.address") 
profile.set_preference("network.proxy.http_port", "port_number") 
profile.update_preferences() 
driver = webdriver.Firefox(firefox_profile=profile) 

para configurar proxy para FF en WebDriver pitón. Esto funciona para FF. ¿Cómo configurar un proxy como este en Chrome? Encontré esto exmaple pero no es muy útil. Cuando ejecuto el script, no pasa nada (el navegador Chrome no se inicia).

+0

Perdón por preguntar lo obvio, pero ¿cambiaste las líneas 'Firefox' por sus equivalentes de Chrome? ¿Podrías enviarme tu código? –

+0

Además, ¿qué quiere decir con "no pasa nada"? ¿Hay un mensaje de error? ¿Un estado de salida de cualquier tipo? –

+0

Noté que si tengo un conjunto de proxy en Internet Explorer, la secuencia de comandos no funciona (FF se abre pero falla en driver.get ("google.com/";)). No hay mensajes de error, se niega a conectarse. La secuencia de comandos funciona si no hay configuraciones de proxy habilitadas en Internet Explorer. – sarbo

Respuesta

35
from selenium import webdriver 

PROXY = "23.23.23.23:3128" # IP:PORT or HOST:PORT 

chrome_options = webdriver.ChromeOptions() 
chrome_options.add_argument('--proxy-server=%s' % PROXY) 

chrome = webdriver.Chrome(chrome_options=chrome_options) 
chrome.get("http://whatismyipaddress.com") 
+1

¿Hay algún método que sin reiniciar el navegador? thx – 176coding

-2
from selenium import webdriver 
from selenium.webdriver.common.proxy import * 

myProxy = "86.111.144.194:3128" 
proxy = Proxy({ 
    'proxyType': ProxyType.MANUAL, 
    'httpProxy': myProxy, 
    'ftpProxy': myProxy, 
    'sslProxy': myProxy, 
    'noProxy':''}) 

driver = webdriver.Firefox(proxy=proxy) 
driver.set_page_load_timeout(30) 
driver.get('http://whatismyip.com') 
+3

No responde la pregunta. – Collin

+1

Chrome: la pregunta era sobre Chrome –

6

Su trabajo para mí ...

from selenium import webdriver 

PROXY = "23.23.23.23:3128" # IP:PORT or HOST:PORT 

chrome_options = webdriver.ChromeOptions() 
chrome_options.add_argument('--proxy-server=http://%s' % PROXY) 

chrome = webdriver.Chrome(chrome_options=chrome_options) 
chrome.get("http://whatismyipaddress.com") 
+0

¿cómo se agrega el nombre de usuario/contraseña si el proxy necesita saltarse? – desmond

4

tuve un problema con la misma cosa. ChromeOptions es muy extraño porque no está integrado con las capacidades deseadas como pensarías. Olvidé los detalles exactos, pero básicamente ChromeOptions restablecerá ciertos valores predeterminados según si pasaste o no una capacidad deseada.

hice lo siguiente mono-parche que me permite especificar la dict sin preocuparse por las complicaciones de la ChromeOptions

cambio el siguiente código en /selenium/webdriver/chrome/webdriver.py:

def __init__(self, executable_path="chromedriver", port=0, 
      chrome_options=None, service_args=None, 
      desired_capabilities=None, service_log_path=None, skip_capabilities_update=False): 
    """ 
    Creates a new instance of the chrome driver. 

    Starts the service and then creates new instance of chrome driver. 

    :Args: 
    - executable_path - path to the executable. If the default is used it assumes the executable is in the $PATH 
    - port - port you would like the service to run, if left as 0, a free port will be found. 
    - desired_capabilities: Dictionary object with non-browser specific 
     capabilities only, such as "proxy" or "loggingPref". 
    - chrome_options: this takes an instance of ChromeOptions 
    """ 
    if chrome_options is None: 
     options = Options() 
    else: 
     options = chrome_options 

    if skip_capabilities_update: 
     pass 
    elif desired_capabilities is not None: 
     desired_capabilities.update(options.to_capabilities()) 
    else: 
     desired_capabilities = options.to_capabilities() 

    self.service = Service(executable_path, port=port, 
     service_args=service_args, log_path=service_log_path) 
    self.service.start() 

    try: 
     RemoteWebDriver.__init__(self, 
      command_executor=self.service.service_url, 
      desired_capabilities=desired_capabilities) 
    except: 
     self.quit() 
     raise 
    self._is_remote = False 

todo lo que cambió fue el kwarg "skip_capabilities_update". Ahora solo hago esto para establecer mi propio dict:

capabilities = dict(DesiredCapabilities.CHROME) 

if not "chromeOptions" in capabilities: 
    capabilities['chromeOptions'] = { 
     'args' : [], 
     'binary' : "", 
     'extensions' : [], 
     'prefs' : {} 
    } 

capabilities['proxy'] = { 
    'httpProxy' : "%s:%i" %(proxy_address, proxy_port), 
    'ftpProxy' : "%s:%i" %(proxy_address, proxy_port), 
    'sslProxy' : "%s:%i" %(proxy_address, proxy_port), 
    'noProxy' : None, 
    'proxyType' : "MANUAL", 
    'class' : "org.openqa.selenium.Proxy", 
    'autodetect' : False 
} 

driver = webdriver.Chrome(executable_path="path_to_chrome", desired_capabilities=capabilities, skip_capabilities_update=True) 
Cuestiones relacionadas