首页 > 解决方案 > 通过 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")

任何帮助将非常感激 :)

标签: pythonpython-3.xseleniumselenium-webdriverselenium-chromedriver

解决方案


如果您需要使用没有身份验证的代理(没有用户名或密码)和 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进行相应的编辑,使参数为假。


推荐阅读