我想将selenium与受密码保护的代理一起使用。代理不是固定的,而是一个变量。所以这必须在代码中完成(只需在这台特定的机器上设置firefox以使用代理就不太理想了)。到目前为止,我有以下代码:
fp = webdriver.FirefoxProfile()
# Direct = 0, Manual = 1, PAC = 2, AUTODETECT = 4, SYSTEM = 5
fp.set_preference("network.proxy.type", 1)
fp.set_preference("network.proxy.http", PROXY_HOST)
fp.set_preference("network.proxy.http_port", PROXY_PORT)
driver = webdriver.Firefox(firefox_profile=fp)
driver.get("http://whatismyip.com")
此时,弹出对话框,请求代理用户/通过。
是否有一种简单的方法:
答案 0 :(得分:18)
硒本身不能做到这一点。我发现有用的唯一方法是Github。简而言之,您需要在执行身份验证时添加浏览器扩展。这比看起来要简单得多。
以下是Chrome的工作原理(在我的例子中):
<强> background.js 强>
var config = {
mode: "fixed_servers",
rules: {
singleProxy: {
scheme: "http",
host: "YOU_PROXY_ADDRESS",
port: parseInt(YOUR_PROXY_PORT)
},
bypassList: ["foobar.com"]
}
};
chrome.proxy.settings.set({value: config, scope: "regular"}, function() {});
function callbackFn(details) {
return {
authCredentials: {
username: "YOUR_PROXY_USERNAME",
password: "YOUR_PROXY_PASSWORD"
}
};
}
chrome.webRequest.onAuthRequired.addListener(
callbackFn,
{urls: ["<all_urls>"]},
['blocking']
);
不要忘记将 YOUR_PROXY _ * 替换为您的设置。
<强>的manifest.json 强>
{
"version": "1.0.0",
"manifest_version": 2,
"name": "Chrome Proxy",
"permissions": [
"proxy",
"tabs",
"unlimitedStorage",
"storage",
"<all_urls>",
"webRequest",
"webRequestBlocking"
],
"background": {
"scripts": ["background.js"]
},
"minimum_chrome_version":"22.0.0"
}
将创建的proxy.zip添加为扩展名
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
chrome_options = Options()
chrome_options.add_extension("proxy.zip")
driver = webdriver.Chrome(executable_path='chromedriver.exe', chrome_options=chrome_options)
driver.get("http://google.com")
driver.close()
就是这样。对我而言,就像一个魅力。如果您需要动态创建proxy.zip或需要PHP示例,请转到here
答案 1 :(得分:2)
受到selenium github repo中单元测试的启发。这对我有用:
from selenium import webdriver
PROXY_HOST = "IP_address"
PROXY_PORT = "your_proxy_port"
USERNAME = "your_user_name"
PASSWORD = "YOUR_PASSWORD"
profile = webdriver.FirefoxProfile()
profile.set_preference("network.proxy.type", 1)
profile.set_preference("network.proxy.http", PROXY_HOST)
profile.set_preference("network.proxy.http_port", PROXY_PORT)
profile.set_preference("network.proxy.socks_username", USERNAME)
profile.set_preference("network.proxy.socks_password", PASSWORD)
profile.update_preferences()
# executable_path = define the path if u don't already have in the PATH system variable.
browser = webdriver.Firefox(firefox_profile=profile)
browser.get('http://website.com')
browser.maximize_window()
答案 2 :(得分:0)
代码对我有用
from selenium import webdriver
browser=webdriver.Firefox()
def login(browser):
alert=browser.switch_to_alert()
alert.send_keys("username"+webdriver.common.keys.Keys.TAB+"password")
alert.accept()
答案 3 :(得分:-6)
你试过PROXY_HOST = "http://username:password@proxy.host.com"
吗?
Also:
从Selenium 2.0 beta 1开始,内置支持 处理弹出对话框。