web-dev-qa-db-fra.com

Exécution de Selenium Webdriver avec un proxy en Python

J'essaie d'exécuter un script Selenium Webdriver en Python pour effectuer certaines tâches de base. Je peux faire en sorte que le robot fonctionne parfaitement lorsqu'il exécute l'interface Selenium IDE (c'est-à-dire: il suffit que l'interface graphique répète mes actions). Cependant, lorsque j'exporte le code en tant que script Python et que je tente de l'exécuter à partir de la ligne de commande, le navigateur Firefox s'ouvre mais ne peut jamais accéder à l'URL de départ (une erreur est renvoyée en ligne de commande et le programme s'arrête). Cela m’arrive quel que soit le site Web auquel je tente d’accéder.

J'ai inclus un code très basique ici à des fins de démonstration. Je ne pense pas que j'ai correctement inclus la section proxy du code car l'erreur renvoyée semble avoir été générée par le proxy.

Toute aide serait extrêmement appréciée. 

Le code ci-dessous est simplement destiné à ouvrir www.google.fr et à rechercher le mot "Selenium". Pour moi, il ouvre un navigateur Firefox vierge et s’arrête.

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 __== "__main__":
    unittest.main()
48
user2479813

Que diriez-vous quelque chose comme ça 

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)

Vous pouvez en lire plus à ce sujet ici .

21
Amey

Cela fonctionne pour moi de cette façon (similaire au code @Amey et @ user4642224, mais un peu plus court):

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)
18
Mykhail Martsyniuk

Ma solution:

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)

Puis appelez votre code:

my_proxy(PROXY_Host,PROXY_PORT)

J'ai eu des problèmes avec ce code parce que je passais une chaîne en tant que port #:

 PROXY_PORT="31280"

C'est important:

int("31280")

Vous devez transmettre un entier au lieu d'une chaîne, sinon votre profil firefox ne sera pas correctement configuré et la connexion par proxy ne fonctionnera pas.

12
mrki

Si quelqu'un cherche une solution, voici comment:

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/')
5
user4642224

Essayez aussi de configurer le proxy socks5. Je faisais face au même problème et il est résolu en utilisant le proxy chaussettes

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)

Ensuite, appelez install_proxy ( ip , port ) à partir de votre programme.

4
chowmean

Essayez en configurant 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")

Ce programme testé sous Windows 8 et Mac OSX. Si vous utilisez Mac OSX et que vous n'avez pas mis à jour Selenium, vous pouvez être confronté à Selenium.common.exceptions.WebDriverException. Si tel est le cas, essayez à nouveau après avoir mis à jour votre Selenium.

pip install -U Selenium
4
Rafayet Ullah

Proxy avec vérification. Ceci est un tout nouveau script python en référence d'un exemple de script Mykhail Martsyniuk.

# Load webdriver
from Selenium import webdriver

# Load proxy option
from Selenium.webdriver.common.proxy import Proxy, ProxyType

# Configure Proxy Option
prox = Proxy()
prox.proxy_type = ProxyType.MANUAL

# Proxy IP & Port
prox.http_proxy = “0.0.0.0:00000”
prox.socks_proxy = “0.0.0.0:00000”
prox.ssl_proxy = “0.0.0.0:00000”

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

# Configure ChromeOptions
driver = webdriver.Chrome(executable_path='/usr/local/share chromedriver',desired_capabilities=capabilities)

# Verify proxy ip
driver.get("http://www.whatsmyip.org/")
1
Mario Uvera

Comme indiqué par @Dugini, certaines entrées de configuration ont été supprimées. Maximal:

webdriver.DesiredCapabilities.FIREFOX['proxy'] = {
    "httpProxy":PROXY,
    "ftpProxy":PROXY,
    "sslProxy":PROXY,
    "noProxy":[],
    "proxyType":"MANUAL"
 }
0
serv-inc

essayez d’exécuter tor service, ajoutez la fonction suivante à votre code.

def connect_tor (port):

socks.set_default_proxy(socks.PROXY_TYPE_SOCKS5, '127.0.0.1', port, True)
socket.socket = socks.socksocket

def main ():

connect_tor()
driver = webdriver.Firefox()
0
o.awajan

Le résultat indiqué ci-dessus est peut-être correct, mais ne fonctionne pas avec le dernier pilote Web. Voici ma solution pour la question ci-dessus. Simple et doux


        http_proxy  = "ip_addr:port"
        https_proxy = "ip_addr:port"

        webdriver.DesiredCapabilities.FIREFOX['proxy']={
            "httpProxy":http_proxy,
            "sslProxy":https_proxy,
            "proxyType":"MANUAL"
        }

        driver = webdriver.Firefox()

OU

    http_proxy  = "http://ip:port"
    https_proxy = "https://ip:port"

    proxyDict = {
                    "http"  : http_proxy,
                    "https" : https_proxy,
                }

    driver = webdriver.Firefox(proxy=proxyDict)
0
Dugini Vijay