使用Python的Selenium:为Firefox输入/提供HTTP代理密码

22 投票
4 回答
28777 浏览
提问于 2025-04-17 10:23

我想用selenium配合一个需要密码的代理。这个代理不是固定的,而是会变的。所以这需要在代码里实现(仅仅在这台机器上设置火狐浏览器使用这个代理并不是最理想的做法)。到目前为止,我有以下的代码:

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")

此时,会弹出一个对话框,要求输入代理的用户名和密码。

有没有简单的方法可以:

  1. 在对话框中输入用户名和密码。
  2. 在更早的阶段提供用户名和密码。

4 个回答

0

Selenium 4 自带了一个处理基本认证的解决方案

// This "HasAuthentication" interface is the key!
HasAuthentication authentication (HasAuthentication) driver;

// You can either register something for all sites
authentication.register(() -> new UsernameAndPassword("admin", "admin"));

// Or use something different for specific sites
authentication.register(
  uri -> uri.getHost().contains("mysite.com"),

new UsernameAndPassword("AzureDiamond", "hunter2"));

https://www.selenium.dev/blog/2021/a-tour-of-4-authentication/

4

这段代码对我来说是有效的。

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() 
29

Selenium本身是做不到这一点的。我找到的唯一有效的方法是在这里有描述。简单来说,你需要在运行时添加一个浏览器扩展来进行身份验证。这比看起来要简单得多。

以下是我在Chrome中使用的方法:

  1. 创建一个名为proxy.zip的压缩文件,里面包含两个文件:

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"
}
  1. 将创建的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的示例,可以去原帖查看。

撰写回答