如何使用Selenium chrome驱动程序Python 3登录到具有身份验证的代理服务器?

时间:2019-06-28 12:01:46

标签: python selenium selenium-webdriver proxy selenium-chromedriver

我正在尝试使用带有selenium chrome驱动程序的python 3登录到我的代理服务器,但是我无法通过右键单击autentication窗口来找到我应该获得哪个元素来推送我的用户名和密码。

这是我尝试过的代码,但是卡在我必须输入用户名和密码的地方。

from selenium import webdriver
username = 'xxxxxxxxxxxxxxxxxxxxxx'
password = 'xxxxxxxxxxxxxxxxxxxxxx'
url = 'http://whatismyipaddress.com'
PROXY = "186.xxx.xx.xx:8000"  # IP:PORT or HOST:PORT
chrome_options = webdriver.ChromeOptions()
chrome_options.add_argument('--proxy-server=%s' % PROXY)
chrome = webdriver.Chrome(options=chrome_options)
chrome.get(url)

它将打开浏览器,并弹出一个小窗口,要求用户和密码。 如何直接用python插入它们? 谢谢

1 个答案:

答案 0 :(得分:0)

让它像这样工作,请注意这段代码的部分不在Python中,只需复制和粘贴,并确保chromedriver.exe在同一目录中。

from selenium import webdriver
import os
import zipfile
url = 'https://whatismyipaddress.com/'
PROXY = 'XXX.XX.XX.XX' # YOUR PROXY IP ADDRESS
port = 'XXXX' # YOUR PORT NUMBER
user = 'XXXXX' # YOUR USER NAME
passw = 'XXXXX' # YOUR PASSWORD
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, port, user, passw)
def get_chromedriver(use_proxy=False, user_agent=None):
    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(url)

只需复制,粘贴并更改您的凭证即可。 确保不要更改任何缩进。 干杯