如何使用Python + Selenium设置代理身份验证(用户和密码) [英] How to set proxy authentication (user & password) using Python + Selenium
问题描述
我正在使用带有Selenium的Python 2.7中的Firefox WebDriver.我的python程序启动Firefox浏览器,并在运行该程序时访问其他网站.但是,我需要设置具有身份验证的代理,以便当程序访问任何网站时,它将通过代理服务器进行访问.
I am using Firefox WebDriver in Python 2.7 with Selenium. My python program starts Firefox browser and visits different websites when I run the program. But, I need to set the proxy with authentication, so that when program visits any website, it will visit through the proxy server.
关于SO也有一些类似的问题.但是,对于Python的Selenium Firefox WebDriver,没有特定的解决方案.
There are some similar questions on SO. But, there is no specific solution for Selenium Firefox WebDriver of Python.
- Python Selenium Webdriver - Proxy Authentication
- Running selenium behind a proxy server
推荐答案
除了运行带有已保存凭据的配置文件的Firefox.您可以加载在chrome://global/content/commonDialog.xul
的loginTextbox
和password1Textbox
(警报窗口)中写入的扩展名.
In addition to running Firefox with a profile which has the credentials saved. You can do it loading an extension that writes in the loginTextbox
and password1Textbox
of chrome://global/content/commonDialog.xul
(the alert window).
已经有一些扩展程序可以完成这项工作.例如:Close Proxy Authentication
There are already some extensions that will do the job. For instance: Close Proxy Authentication
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)
这篇关于如何使用Python + Selenium设置代理身份验证(用户和密码)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!