2013-06-13 12 views
32

Sto tentando di eseguire uno script Selenium Webdriver in Python per eseguire alcune attività di base. Riesco a far funzionare il robot perfettamente quando lo si esegue attraverso l'interfaccia IDE Selenium (ovvero: quando si ottiene semplicemente la GUI per ripetere le mie azioni). Tuttavia, quando esporto il codice come script Python e provo ad eseguirlo dalla riga di comando, il browser Firefox si aprirà ma non potrà mai accedere all'URL iniziale (viene restituito un errore alla riga di comando e il programma si ferma). Questo mi sta accadendo a prescindere dal sito Web che sto cercando di accedere.In esecuzione Selenium Webdriver con un proxy in Python

Ho incluso un codice molto semplice qui a scopo dimostrativo. Non penso di aver incluso correttamente la sezione proxy del codice poiché l'errore che viene restituito sembra essere generato dal proxy.

Qualsiasi aiuto sarebbe molto apprezzato.

Il seguente codice ha il solo scopo di aprire www.google.ie e cercare la parola "selenio". Per me apre un browser Firefox vuoto e si ferma.

from selenium import webdriver 
from selenium.webdriver.common.by import By 
from selenium.webdriver.support.ui import Select 
from selenium.common.exceptions import NoSuchElementException 
import unittest, time, re 
from selenium.webdriver.common.proxy import * 

class Testrobot2(unittest.TestCase): 
    def setUp(self): 

     myProxy = "http://149.215.113.110:70" 

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

     self.driver = webdriver.Firefox(proxy=proxy) 
     self.driver.implicitly_wait(30) 
     self.base_url = "https://www.google.ie/" 
     self.verificationErrors = [] 
     self.accept_next_alert = True 

    def test_robot2(self): 
     driver = self.driver 
     driver.get(self.base_url + "/#gs_rn=17&gs_ri=psy-ab&suggest=p&cp=6&gs_id=ix&xhr=t&q=selenium&es_nrs=true&pf=p&output=search&sclient=psy-ab&oq=seleni&gs_l=&pbx=1&bav=on.2,or.r_qf.&bvm=bv.47883778,d.ZGU&fp=7c0d9024de9ac6ab&biw=592&bih=665") 
     driver.find_element_by_id("gbqfq").clear() 
     driver.find_element_by_id("gbqfq").send_keys("selenium") 

    def is_element_present(self, how, what): 
     try: self.driver.find_element(by=how, value=what) 
     except NoSuchElementException, e: return False 
     return True 

    def is_alert_present(self): 
     try: self.driver.switch_to_alert() 
     except NoAlertPresentException, e: return False 
     return True 

    def close_alert_and_get_its_text(self): 
     try: 
      alert = self.driver.switch_to_alert() 
      alert_text = alert.text 
      if self.accept_next_alert: 
       alert.accept() 
      else: 
       alert.dismiss() 
      return alert_text 
     finally: self.accept_next_alert = True 

    def tearDown(self): 
     self.driver.quit() 
     self.assertEqual([], self.verificationErrors) 

if __name__ == "__main__": 
    unittest.main() 

risposta

13

Che ne dite di qualcosa di simile

PROXY = "149.215.113.110:70" 

webdriver.DesiredCapabilities.FIREFOX['proxy'] = { 
    "httpProxy":PROXY, 
    "ftpProxy":PROXY, 
    "sslProxy":PROXY, 
    "noProxy":None, 
    "proxyType":"MANUAL", 
    "class":"org.openqa.selenium.Proxy", 
    "autodetect":False 
} 

# you have to use remote, otherwise you'll have to code it yourself in python to 
driver = webdriver.Remote("http://localhost:4444/wd/hub", webdriver.DesiredCapabilities.FIREFOX) 

Si può leggere di più su di esso here.

+0

Questa risposta ha funzionato bene per me . Nel caso in cui qualcun altro stia tentando di farlo con Edge, 'webdriver.DesiredCapabilities.EDGE ['proxy']' non ha alcun effetto perché attualmente Microsoft Edge non ha un'impostazione per configurare un server proxy (per utilizzare Edge con un proxy, è necessario configurare il proxy nelle impostazioni di connessione di rete di Windows). –

+1

Per il documento dettagliato completo, consultare: https://github.com/SeleniumHQ/selenium/wiki/DesiredCapabilities#proxy-json-object – LeckieNi

10

La mia soluzione:

def my_proxy(PROXY_HOST,PROXY_PORT): 
     fp = webdriver.FirefoxProfile() 
     # Direct = 0, Manual = 1, PAC = 2, AUTODETECT = 4, SYSTEM = 5 
     print PROXY_PORT 
     print PROXY_HOST 
     fp.set_preference("network.proxy.type", 1) 
     fp.set_preference("network.proxy.http",PROXY_HOST) 
     fp.set_preference("network.proxy.http_port",int(PROXY_PORT)) 
     fp.set_preference("general.useragent.override","whater_useragent") 
     fp.update_preferences() 
     return webdriver.Firefox(firefox_profile=fp) 

quindi chiamare nel codice:

my_proxy(PROXY_HOST,PROXY_PORT) 

ho avuto problemi con questo codice, perché stavo passando una stringa come una porta #:

PROXY_PORT="31280" 

Importante:

int("31280") 

È necessario passare un numero intero anziché una stringa oppure il proprio profilo firefox non verrà impostato su una porta corretta e la connessione tramite proxy non funzionerà.

+1

La porta deve essere convertita in int? Ciò renderebbe errato l'esempio del proxy di Firefox sulla pagina ufficiale: http://www.seleniumhq.org/docs/04_webdriver_advanced.jsp Nel loro esempio, PROXYHOST: PROXYPORT è passato come una stringa. – Pyderman

+0

@Pyderman, stai confondendo la classe 'Proxy()' con la classe 'FirefoxProfile()'. Usando le preferenze del profilo devi passare ip e porta separatamente, e lanciare 'port' su' int() '. Nella classe 'Proxy()' passi semplicemente la stringa contenente "IP: PORT", e sicuramente fa il resto del lavoro per te. – erm3nda

4

Prova anche a configurare il proxy sock5. Ero di fronte lo stesso problema e si è risolto tramite proxy SOCKS

def install_proxy(PROXY_HOST,PROXY_PORT): 
     fp = webdriver.FirefoxProfile() 
     print PROXY_PORT 
     print PROXY_HOST 
     fp.set_preference("network.proxy.type", 1) 
     fp.set_preference("network.proxy.http",PROXY_HOST) 
     fp.set_preference("network.proxy.http_port",int(PROXY_PORT)) 
     fp.set_preference("network.proxy.https",PROXY_HOST) 
     fp.set_preference("network.proxy.https_port",int(PROXY_PORT)) 
     fp.set_preference("network.proxy.ssl",PROXY_HOST) 
     fp.set_preference("network.proxy.ssl_port",int(PROXY_PORT)) 
     fp.set_preference("network.proxy.ftp",PROXY_HOST) 
     fp.set_preference("network.proxy.ftp_port",int(PROXY_PORT)) 
     fp.set_preference("network.proxy.socks",PROXY_HOST) 
     fp.set_preference("network.proxy.socks_port",int(PROXY_PORT)) 
     fp.set_preference("general.useragent.override","Mozilla/5.0 (Macintosh; Intel Mac OS X 10_9_3) AppleWebKit/537.75.14 (KHTML, like Gecko) Version/7.0.3 Safari/7046A194A") 
     fp.update_preferences() 
     return webdriver.Firefox(firefox_profile=fp) 

Quindi chiamare install_proxy (ip , port) dal programma.

+0

mi ha risparmiato un sacco di tempo –

3

Se qualcuno è alla ricerca di una soluzione ecco come:

from selenium import webdriver 
PROXY = "YOUR_PROXY_ADDRESS_HERE" 
webdriver.DesiredCapabilities.FIREFOX['proxy']={ 
    "httpProxy":PROXY, 
    "ftpProxy":PROXY, 
    "sslProxy":PROXY, 
    "noProxy":None, 
    "proxyType":"MANUAL", 
    "autodetect":False 
} 
driver = webdriver.Firefox() 
driver.get('http://www.whatsmyip.org/') 
2

Try attraverso la creazione di FirefoxProfile

from selenium import webdriver 
import time 


"Define Both ProxyHost and ProxyPort as String" 
ProxyHost = "54.84.95.51" 
ProxyPort = "8083" 



def ChangeProxy(ProxyHost ,ProxyPort): 
    "Define Firefox Profile with you ProxyHost and ProxyPort" 
    profile = webdriver.FirefoxProfile() 
    profile.set_preference("network.proxy.type", 1) 
    profile.set_preference("network.proxy.http", ProxyHost) 
    profile.set_preference("network.proxy.http_port", int(ProxyPort)) 
    profile.update_preferences() 
    return webdriver.Firefox(firefox_profile=profile) 


def FixProxy(): 
    ""Reset Firefox Profile"" 
    profile = webdriver.FirefoxProfile() 
    profile.set_preference("network.proxy.type", 0) 
    return webdriver.Firefox(firefox_profile=profile) 


driver = ChangeProxy(ProxyHost ,ProxyPort) 
driver.get("http://whatismyipaddress.com") 

time.sleep(5) 

driver = FixProxy() 
driver.get("http://whatismyipaddress.com") 

Questo programma testato sia su Windows 8 e Mac OSX. Se stai usando Mac OSX e se non hai aggiornato il selenio, potresti dover affrontare selenium.common.exceptions.WebDriverException.Se è così, quindi riprovare dopo l'aggiornamento del selenio

pip install -U selenium 
6

funziona per me in questo modo (simile a @Amey e @ user4642224 codice, ma più corto un po '):

from selenium import webdriver 
from selenium.webdriver.common.proxy import Proxy, ProxyType 

prox = Proxy() 
prox.proxy_type = ProxyType.MANUAL 
prox.http_proxy = "ip_addr:port" 
prox.socks_proxy = "ip_addr:port" 
prox.ssl_proxy = "ip_addr:port" 

capabilities = webdriver.DesiredCapabilities.CHROME 
prox.add_to_capabilities(capabilities) 

driver = webdriver.Chrome(desired_capabilities=capabilities)