如何让Selenium WebDriver使用Socks代理?

时间:2014-09-20 14:51:30

标签: python selenium-webdriver

我有这段代码:

proxy = Proxy({
    'proxyType': ProxyType.MANUAL,
    "socksProxy": "192.200.208.5:80", #edited
    "socksUsername" :"username", #edited
    "socksPassword" : "password", #edited
    'noProxy':''})

driver = webdriver.Firefox(proxy=proxy)
driver.get('http://whatismyip.com')

当我执行此脚本时,它会打开一个Firefox浏览器,但在加载页面时会“卡住”。如果我改为使用此代码:

PROXY = "192.200.208.5:80:username:password"
proxy = Proxy({
    "httpProxy":PROXY,
    "ftpProxy":PROXY,
    "sslProxy":PROXY,
    'proxyType': ProxyType.MANUAL,
    'noProxy':''})

我被要求在弹出窗口中填写我的代理的用户名/密码。当我输入凭据时,它会正常加载whatismyip.com,我可以看到我正在使用代理。

我希望这会自动发生,但我不确定为什么上面的代码不起作用。

我不确定代理是否是“socks”代理,但它是唯一拥有用户名/密码的代理,所以我认为我的方向正确。

1 个答案:

答案 0 :(得分:2)

让我们先了解一下,FF(或你与Selenium一起使用的webdriver)是如何设置SOCKS代理的。

对于Firefox,请在URL框中执行:config。

network.proxy.socks;10.10.10.1
network.proxy.socks_port;8999
network.proxy.socks_remote_dns;true
network.proxy.socks_version;5

您可以在FF profile director中的prefs.js中看到相同内容,如下所示:

user_pref("network.proxy.socks", "10.10.10.1");
user_pref("network.proxy.socks_port", 8999);
user_pref("network.proxy.type", 1);

请注意,network.proxy.socks是字符串,应该只设置为字符串。 network.proxy.socks_port也必须是int。

使用selenium python模块进行设置时:

from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.proxy import *
import time

# for fresh FF profile
#profile = webdriver.FirefoxProfile() 
profile_path="/path/to/custom/profile/"
profile = webdriver.FirefoxProfile(profile_path)
# set FF preference to socks proxy
profile.set_preference("network.proxy.type", 1)
profile.set_preference("network.proxy.socks", "10.10.10.1")
profile.set_preference("network.proxy.socks_port", 8999)
profile.set_preference("network.proxy.socks_version", 5)
profile.update_preferences()
driver = webdriver.Firefox(firefox_profile=profile)

driver.get("http://whatismyip.com")
print driver.page_source
# sleep if want to show in gui mode. we do print it in cmd
time.sleep(25)
driver.close()
driver.quit()

请检查是否支持给定的首选项并在FF中显示:config list。我没有看到对SOCKS代理的信任支持。