Skip to main content
 首页 » 编程设计

python之如何让 Selenium WebDriver 使用 Socks 代理

2024年08月27日46zlslch

我有这个代码:

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”代理,但它是唯一具有用户名/密码的代理,所以我认为我的方向是正确的。

请您参考如下方法:

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

对于 Firefox,在 URL 框中执行 about: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 about:config 列表中。我没有看到对 SOCKS 代理的信用支持。