我有这个代码:
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 配置文件管理器的 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 代理的信用支持。
关于python - 如何让 Selenium WebDriver 使用 Socks 代理?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25949997/