python - 通过 Selenium chromedriver 进行 Python 代理身份验证
问题描述
我们尝试了几天在 Python 中使用 selenium chromedriver 设置代理身份验证。我们无法设置 ip,因为 Chrome 会弹出一个用于身份验证的弹出窗口。问题是 selenium 不能切换到那个窗口,所以不能打字。唯一对我们有用的解决方案是使用 pyautogui,这对我们来说是一个糟糕的解决方案,因为我们想使用 headless 功能。
以下是我们尝试过的所有方法:
driver.switch_to_window()
driver.switch_to_active_element()
driver.switch_to_alert()
ActionChains(driver).send_keys("test").perform()
driver.switch_to_alert()
options = webdriver.ChromeOptions()
options.add_argument('--proxy-server=http://user:pass@3.223.68.195:31112')
driver.get("https://user:pass@google.com")
proxy = {'address': '3.209.253.119:31112',
'username': 'user',
'password': 'pass'}
capabilities = dict(DesiredCapabilities.CHROME)
capabilities['proxy'] = {'proxyType': 'MANUAL',
'httpProxy': proxy['address'],
'ftpProxy': proxy['address'],
'sslProxy': proxy['address'],
'noProxy': '',
'class': "org.openqa.selenium.Proxy",
'autodetect': False}
capabilities['proxy']['socksUsername'] = proxy['username']
capabilities['proxy']['socksPassword'] = proxy['password']
driver = webdriver.Chrome(executable_path="chromedriver.exe", desired_capabilities=capabilities)
driver.get("http://google.com")
任何帮助将非常感激 :)
解决方案
如果您需要使用没有身份验证的代理(没有用户名或密码)和 python 和 Selenium 库和 chromedriver,您通常使用以下代码:
chrome_options = webdriver.ChromeOptions()
chrome_options.add_argument('--proxy-server=%s' % hostname + ":" + port)
driver = webdriver.Chrome(chrome_options=chrome_options)
除非代理需要身份验证,否则它工作正常。如果代理要求您使用用户名和密码登录,它将不起作用。在这种情况下,您必须使用下面解释的更棘手的解决方案。
要设置代理身份验证,我们将生成一个文件并使用以下代码将其动态上传到 chromedriver。这有效地创建了一个 chrome 扩展。此代码使用 chromedriver 配置 selenium 以使用需要使用用户/密码对进行身份验证的 HTTP 代理。
import os
import zipfile
from selenium import webdriver
def create_chromedriver(PROXY_HOST, PROXY_PORT, PROXY_USER, PROXY_PASS, USER_AGENT):
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"
}
"""
background_js = """
var config = {
mode: "fixed_servers",
rules: {
singleProxy: {
scheme: "http",
host: "%s",
port: parseInt(%s)
},
bypassList: ["localhost"]
}
};
chrome.proxy.settings.set({value: config, scope: "regular"}, function() {});
function callbackFn(details) {
return {
authCredentials: {
username: "%s",
password: "%s"
}
};
}
chrome.webRequest.onAuthRequired.addListener(
callbackFn,
{urls: ["<all_urls>"]},
['blocking']
);
""" % (PROXY_HOST, PROXY_PORT, PROXY_USER, PROXY_PASS)
def get_chromedriver(use_proxy=True, user_agent=USER_AGENT):
path = os.path.dirname(os.path.abspath(__file__))
chrome_options = webdriver.ChromeOptions()
if use_proxy:
pluginfile = 'proxy_auth_plugin.zip'
with zipfile.ZipFile(pluginfile, 'w') as zp:
zp.writestr("manifest.json", manifest_json)
zp.writestr("background.js", background_js)
chrome_options.add_extension(pluginfile)
if user_agent:
chrome_options.add_argument('--user-agent=%s' % USER_AGENT)
driver = webdriver.Chrome(
os.path.join(path, 'chromedriver'),
chrome_options=chrome_options)
return driver
driver = get_chromedriver(use_proxy=True)
# driver.get('https://www.google.com/search?q=my+ip+address')
driver.get('https://httpbin.org/ip')
user_agent = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/86.0.4240.198 Safari/537.36'
create_chromedriver('192.168.3.2', 8080, 'user', 'pass', user_agent)
函数get_chromedriver
返回可在应用程序中使用的已配置 selenium Web 驱动程序。此代码经过测试并且工作正常。
要将其实现到您自己的代码中,只需create_chromedriver
使用主机、端口、用户、通行证和用户代理的参数调用该函数。如果您不想使用代理或用户代理,只需get_chromedriver
进行相应的编辑,使参数为假。
推荐阅读
- scala - 无法使用 shapeless 派生类型类的隐式实例
- turing-machines - 在图灵机中将两个二进制数相乘
- botframework - BotFramework Composer:避免来自 LUIS 的不必要中断,但支持跨对话框“取消”?
- python - 永久更改 Microsoft Access DB 的密码(通过 Python)
- python-3.x - 如何在 Macbook 本地、远程 Linux 服务器上处理 Python 项目?
- reactjs - 将数据传递给 IonReactRouter 中的子级
- sql - 将表中的字符串转换为用于选择另一个表的列
- c - 如何在C中的`execv`中组合`lshw`和`grep`命令?
- firebase - 更新现有文档中的一个字段是否被视为写入?
- javascript - 为什么我不能使用 html 和 javascript 中的搜索功能?