简体   繁体   English

如何使用 Python + Selenium 设置代理身份验证(用户和密码)

[英]How to set proxy authentication (user & password) using Python + Selenium

I am using Firefox WebDriver in Python 2.7 with Selenium.我在带有 Selenium 的 Python 2.7 中使用 Firefox WebDriver。 My python program starts Firefox browser and visits different websites when I run the program.当我运行程序时,我的 python 程序会启动 Firefox 浏览器并访问不同的网站。 But, I need to set the proxy with authentication, so that when program visits any website, it will visit through the proxy server.但是,我需要设置带身份验证的代理,这样当程序访问任何网站时,它都会通过代理服务器访问。

There are some similar questions on SO. SO上有一些类似的问题。 But, there is no specific solution for Selenium Firefox WebDriver of Python.但是,没有针对 Python 的 Selenium Firefox WebDriver 的具体解决方案。

Dup of: How to set proxy AUTHENTICATION username:password using Python/Selenium重复: 如何使用 Python/Selenium 设置代理身份验证用户名:密码

Selenium-wire: https://github.com/wkeeling/selenium-wire硒线: https : //github.com/wkeeling/selenium-wire

Install selenium-wire安装硒线

pip install selenium-wire

Import it导入它

from seleniumwire import webdriver

Auth to proxy授权代理

options = {
'proxy': {
    'http': 'http://username:password@host:port',
    'https': 'https://username:password@host:port',
    'no_proxy': 'localhost,127.0.0.1,dev_server:8080'
    }
}
driver = webdriver.Firefox(seleniumwire_options=options)

Warning警告
Take a look to the selenium-wire cache folder.查看 selenium-wire 缓存文件夹。 I had a problem because it take all my disk space.我遇到了问题,因为它占用了我所有的磁盘空间。 You have to remove it sometimes in your script when you want.您有时必须在需要时在脚本中将其删除。

In addition to running Firefox with a profile which has the credentials saved.除了使用保存了凭据的配置文件运行 Firefox 之外。 You can do it loading an extension that writes in the loginTextbox and password1Textbox of chrome://global/content/commonDialog.xul (the alert window).您可以加载一个扩展名,该扩展名写入chrome://global/content/commonDialog.xul (警报窗口)的loginTextboxpassword1Textbox

There are already some extensions that will do the job.已经有一些扩展可以完成这项工作。 For instance: Close Proxy Authentication例如: Close Proxy Authentication

https://addons.mozilla.org/firefox/downloads/latest/close-proxy-authentication/addon-427702-latest.xpi https://addons.mozilla.org/firefox/downloads/latest/close-proxy-authentication/addon-427702-latest.xpi

from selenium import webdriver
from base64 import b64encode

proxy = {'host': HOST, 'port': PORT, 'usr': USER, 'pwd': PASSWD}

fp = webdriver.FirefoxProfile()

fp.add_extension('closeproxy.xpi')
fp.set_preference('network.proxy.type', 1)
fp.set_preference('network.proxy.http', proxy['host'])
fp.set_preference('network.proxy.http_port', int(proxy['port']))
# ... ssl, socks, ftp ...
fp.set_preference('network.proxy.no_proxies_on', 'localhost, 127.0.0.1')

credentials = '{usr}:{pwd}'.format(**proxy)
credentials = b64encode(credentials.encode('ascii')).decode('utf-8')
fp.set_preference('extensions.closeproxyauth.authtoken', credentials)

driver = webdriver.Firefox(fp)

You can write own firefox extension for proxy, and launch from selenium.您可以为代理编写自己的 firefox 扩展,并从 selenium 启动。 You need write 2 files and pack it.你需要写2个文件并打包。

background.js背景.js

var proxy_host = "YOUR_PROXY_HOST";
var proxy_port = YOUR_PROXY_PORT;

var config = {
    mode: "fixed_servers",
    rules: {
      singleProxy: {
        scheme: "http",
        host: proxy_host,
        port: proxy_port
      },
      bypassList: []
    }
 };


function proxyRequest(request_data) {
    return {
        type: "http",
        host: proxy_host, 
        port: proxy_port
    };
}

browser.proxy.settings.set({value: config, scope: "regular"}, function() {;});

function callbackFn(details) {
return {
    authCredentials: {
        username: "YOUR_USERNAME",
        password: "YOUR_PASSWORD"
    }
};
}

browser.webRequest.onAuthRequired.addListener(
        callbackFn,
        {urls: ["<all_urls>"]},
        ['blocking']
);

browser.proxy.onRequest.addListener(proxyRequest, {urls: ["<all_urls>"]});

manifest.json清单文件

{
  "name": "My Firefox Proxy",
  "version": "1.0.0b",
  "manifest_version": 2,
  "permissions": [
    "browsingData",
    "proxy",
    "storage",
    "tabs",
    "webRequest",
    "webRequestBlocking",
    "downloads",
    "notifications",
    "<all_urls>"
  ],
  "background": {
    "scripts": ["background.js"]
  },
  "browser_specific_settings": {
    "gecko": {
      "id": "myproxy@example.org"
    }
  }
}

Next you need packed this files to zip archive in DEFLATED mode with .xpi at end like my_proxy_extension.xpi .接下来,您需要将此文件打包为压缩文件,以 DEFLATED 模式将 .xpi 压缩到结尾,如my_proxy_extension.xpi

You have two choices:你有两个选择:

  1. Sign your extension Firefox extension .xpi file structure: description, contents, creation, and installation签署您的扩展Firefox 扩展 .xpi 文件结构:描述、内容、创建和安装

OR

  1. Run unsigned.运行未签名。 For this step:对于这一步:

    1. Open firefox flags at about:config and set options xpinstall.signatures.required to false在 about:config 中打开 firefox 标志并将选项xpinstall.signatures.required设置为false

      OR

    2. Update firefox profile in:在以下位置更新 Firefox 配置文件:

      Windows : C:\\Program Files\\Mozilla Firefox\\defaults\\pref\\channel-prefs.js Windows : C:\\Program Files\\Mozilla Firefox\\defaults\\pref\\channel-prefs.js

      Linux : /etc/firefox/syspref.js Linux :/etc/firefox/syspref.js

    Add next line to end of file:将下一行添加到文件末尾:

     pref("xpinstall.signatures.required",false);

After this steps run selenium and install this extension:在此步骤之后运行 selenium 并安装此扩展:

from selenium import webdriver

driver = webdriver.Firefox()
driver.install_addon("path/to/my_proxy_extension.xpi")

driver.get("https://yoursite.com")


 

There is an example for Firefox + Python but without the authentication here .有一个 Firefox + Python 的例子,但这里没有认证。 Then you can find other available parameters here in source code.然后,你可以找到其他可用的参数在这里的源代码。 So it looks like you need the following:所以看起来你需要以下内容:

socksUsername
socksPassword

For example:例如:

from selenium import webdriver
from selenium.webdriver.common.proxy import *

myProxy = "host:8080"

proxy = Proxy({
    'proxyType': ProxyType.MANUAL,
    'httpProxy': myProxy, # set this value as desired
    'ftpProxy': myProxy,  # set this value as desired
    'sslProxy': myProxy,  # set this value as desired
    'noProxy': ''         # set this value as desired
    'socksUsername': = ''
    'socksPassword': = ''
    })

driver = webdriver.Firefox(proxy=proxy)

or with preferences:或有偏好:

driverPref = webdriver.FirefoxProfile()
driverPref.set_preference("network.proxy.type", 1)
.
.
.
driverPref.set_preference('network.proxy.socks', proxyHost)
driverPref.set_preference('network.proxy.socks_port', proxyPort)
driverPref.update_preferences()

driver = webdriver.Firefox(firefox_profile=driverPref)

EDIT :编辑

I looked at it again and it seems that it is impossible to set authentication details in FF, even manually.我又看了一遍,好像在FF中设置认证细节是不可能的,手动也是不行的。 The only way is just to remember the details that you have already entered which done by 2 parameters:唯一的方法是记住您已经输入的详细信息,这些详细信息由 2 个参数完成:

signon.autologin.proxy=true
network.websocket.enabled=false

that can be configured with the set_preference() method.可以使用set_preference()方法进行配置。 You can also manually view all FF options by browsing to about:config .您还可以通过浏览到about:config手动查看所有 FF 选项。

In an addition to the answer with extension.除了答案与扩展。

You can also use form filling to dynamically change credentials on your proxy.您还可以使用表单填写来动态更改代理上的凭据。 Just load the extension page, fill the form automatically and click save!只需加载扩展页面,自动填写表格并点击保存!

We can switch to authentication alert box and enter username password manually.我们可以切换到认证提示框,手动输入用户名密码。

profile = webdriver.FirefoxProfile()
profile.set_preference("network.proxy.type", 1)
profile.set_preference('network.proxy.ssl_port', int(ProxyPort))
profile.set_preference('network.proxy.ssl', ProxyHost)
profile.set_preference("network.proxy.http", ProxyHost)
profile.set_preference("network.proxy.http_port", int(ProxyPort))

webdriver = webdriver.Firefox(firefox_profile=profile, executable_path=GECKO_DRIVER_PATH)

webdriver.get("https://whatismyipaddress.com/")
try:
    alert = webdriver.switch_to_alert()
    print("switched to alert window")
    alert.send_keys(proxy_username + Keys.TAB + proxy_password)
    alert.accept()
    webdriver.switch_to.default_content()
except Exception:
    print("Error in alert switch")
    pass

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM