通过 Selenium chromedriver 进行 Python 代理身份验证

标签 python python-3.x selenium selenium-webdriver selenium-chromedriver

我们尝试了几天在 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")
任何帮助将非常感激 :)

最佳答案

如果您需要使用带有 chromedriver 的 python 和 Selenium 库的无身份验证(无用户名或密码)的代理,您通常使用以下代码:

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因此,args 是错误的。

关于通过 Selenium chromedriver 进行 Python 代理身份验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64829313/

相关文章:

java - 元素不可见 Selenium

java - 如何在java selenium中xpath这个 "Policy"选项卡

python - PyQt4 高亮显示

python - 如何知道在python中为不同的属性分配相同的值哪个更有优势

python - 如何从内存中播放 Wav 声音样本

Python Openpyxl ...删除具有特定单词的行

python-3.x - Python3 正确安装 PyCurl

python - 进程间共享锁

python - 无法获得所需的部分而将其余部分踢出

javascript - 如何在 webdriverjs 中等待 takeScreenshot 截取屏幕截图