您现在的位置是:网站首页>文章详情文章详情
selenium设置带用户名密码认证的代理和不认证的代理
inlike2019-11-23【 原创文章 】 浏览(3532) 评论(0) 喜欢(30)
简介selenium设置不认证的代理很简单,但是设置需要用户名密码认证的代理就没有提供这个功能了
认证代理见:https ://vimmaniac.com/blog/bangal/selenium-chrome-driver-proxy-with-authentication,内容如下:
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
def create_proxyauth_extension(proxy_host, proxy_port,
proxy_username, proxy_password,
scheme='http', plugin_path=None):
"""Proxy Auth Extension
args:
proxy_host (str): domain or ip address, ie proxy.domain.com
proxy_port (int): port
proxy_username (str): auth username
proxy_password (str): auth password
kwargs:
scheme (str): proxy scheme, default http
plugin_path (str): absolute path of the extension
return str -> plugin_path
"""
import string
import zipfile
if plugin_path is None:
plugin_path = 'vimm_chrome_proxyauth_plugin.zip'
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 = string.Template(
"""
var config = {
mode: "fixed_servers",
rules: {
singleProxy: {
scheme: "${scheme}",
host: "${host}",
port: parseInt(${port})
},
bypassList: ["foobar.com"]
}
};
chrome.proxy.settings.set({value: config, scope: "regular"}, function() {});
function callbackFn(details) {
return {
authCredentials: {
username: "${username}",
password: "${password}"
}
};
}
chrome.webRequest.onAuthRequired.addListener(
callbackFn,
{urls: ["<all_urls>"]},
['blocking']
);
"""
).substitute(
host=proxy_host,
port=proxy_port,
username=proxy_username,
password=proxy_password,
scheme=scheme,
)
with zipfile.ZipFile(plugin_path, 'w') as zp:
zp.writestr("manifest.json", manifest_json)
zp.writestr("background.js", background_js)
return plugin_path
proxyauth_plugin_path = create_proxyauth_extension(
proxy_host="proxy.crawlera.com",
proxy_port=8010,
proxy_username="fea687a8b2d448d5a5925ef1dca2ebe9",
proxy_password=""
)
co = Options()
co.add_argument("--start-maximized")
co.add_extension(proxyauth_plugin_path)
driver = webdriver.Chrome(chrome_options=co)
driver.get("http://www.whatsmybrowser.org/")
其思路是通过定制一个浏览器的插件来实现,上述功能在Chrome浏览器上可以完美使用。
当然不用认证的代理就很简单了,如下:
from selenium import webdriver
options = webdriver.ChromeOptions()
options.add_argument("--proxy-server=http://{}".format(ip) # 注意格式:ip:proxy
driver = webdriver.Chrome(chrome_options=options)
检验代理成功与否,可用下面的网址:
http://pv.sohu.com/cityjson?ie=utf-8
相关文章
本栏推荐
标签云
猜你喜欢
站点信息
- 建站时间:2019-5-24
- 网站程序:like in love
- 主题模板:《今夕何夕》
- 文章统计:104条
- 文章评论:***条
- 微信公众号:扫描二维码,关注我们