以下为各种尝试的记录,正确实现可直接参考最后一条!
1,导入Proxy库来添加capabilities属性:可以访问网站,但ip还是本机ip
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.common.proxy import Proxy, ProxyType
import timedef get_proxy():proxy_host = "xxx" # 获取隧道服务器地址proxy_port = "xxx" # 获取隧道服务器端口key = "xxx" # 用户keypasswd = "xxx" # 用户密码proxies = Proxy({'proxyType': ProxyType.MANUAL,'httpProxy': '{}:{}@{}:{}'.format(key, passwd, proxy_host, proxy_port),'httpsProxy': '{}:{}@{}:{}'.format(key, passwd, proxy_host, proxy_port),})return proxieschrome_options = Options()
chrome_options.add_argument("--no-sandbox")
chrome_options.add_experimental_option("excludeSwitches", ["enable-automation"])proxy = get_proxy()
capabilities = webdriver.DesiredCapabilities.CHROME.copy()
proxy.add_to_capabilities(capabilities)
# 启动浏览器
browser = webdriver.Chrome(options=chrome_options, desired_capabilities=capabilities)
browser.maximize_window()
browser.get("http://httpbin.org/ip")
time.sleep(2)
browser.quit()
2,直接options增加‘–proxy-server’:访问网页失败
proxy_auth = f"key:passwd@proxy_host:proxy_port"chrome_options.add_argument(f'--proxy-server={proxy_auth}')
3,以下代码可以打开网站,但是没有自动输入账号密码
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.common.proxy import Proxy, ProxyType
import time# 设置代理IP
proxy_ip = "xxx" # 获取隧道服务器地址
proxy_port = "xxx" # 获取隧道服务器端口
proxy_username = "xxx" # 用户key
proxy_password = "xxx" # 用户密码# 设置代理
proxy = Proxy()
proxy.proxy_type = ProxyType.MANUAL
proxy.http_proxy = f"{proxy_ip}:{proxy_port}"# 配置代理的认证信息
capabilities = webdriver.DesiredCapabilities.CHROME.copy()
proxy_auth = f"{proxy_username}:{proxy_password}"
capabilities['proxy'] = {'httpProxy': proxy.http_proxy,'ftpProxy': proxy.http_proxy,'sslProxy': proxy.http_proxy,'proxyType': 'MANUAL','socksUsername': proxy_username,'socksPassword': proxy_password
}chrome_options = Options()
chrome_options.add_argument("--no-sandbox")
chrome_options.add_experimental_option("excludeSwitches", ["enable-automation"])browser = webdriver.Chrome(options=chrome_options)
browser.maximize_window()
browser.get("http://httpbin.org/ip")
time.sleep(2)
browser.quit()
4,查询博客:https://cloud.tencent.com/developer/article/2376251
Selenium-Chrome-HTTP-Private-Proxy HTTP 代理解决方案
默认情况下,Chrome的–proxy-server="http://ip:port"参数不支持设置用户名和密码认证。因此"Selenium + Chrome Driver"无法使用HTTP Basic Authentication的HTTP代理。一种变通的方式就是采用IP地址认证,但在国内网络环境下,大多数用户都采用ADSL形式网络接入,IP是变化的,也无法采用IP地址绑定认证。因此迫切需要找到一种让Chrome自动实现HTTP代理用户名密码认证的方案。
Stackoverflow上有人分享了一种利用Chrome插件实现自动代理用户密码认证的方案非常不错,详细地址:http://stackoverflow.com/questions/9888323/how-to-override-basic-authentication-in-selenium2-with-java-using-chrome-driver
鲲之鹏的技术人员在此思路的基础上用Python实现了自动化的Chrome插件创建过程,即根据指定的代理“username:password@ip:port”自动创建一个Chrome代理插件,然后可以在"Selenium + Chrome Driver"中通过安装该插件实现代理配置功能(插件地址:https://github.com/RobinDev/Selenium-Chrome-HTTP-Private-Proxy)
如何实现
1.访问插件地址下载插件,放在项目目录中供使用
2.编写代码
import time
import string
import zipfile
from selenium import webdriver
from selenium.webdriver.chrome.options import Optionsdef create_proxyauth_extension(proxy_host, proxy_port,proxy_username, proxy_password,scheme='http', plugin_path=None):"""Proxy Auth Extensionargs:proxy_host (str): domain or ip address, ie proxy.domain.comproxy_port (int): portproxy_username (str): auth usernameproxy_password (str): auth passwordkwargs:scheme (str): proxy scheme, default httpplugin_path (str): absolute path of the extensionreturn str -> plugin_path"""if plugin_path is None:plugin_path = 'Selenium-Chrome-HTTP-Private-Proxy.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_pathdef configure_headless_browser(proxy_config):chrome_options = Options()chrome_options.add_argument("--start-maximized")proxyauth_plugin_path = create_proxyauth_extension(proxy_host=proxy_config[0],proxy_port=proxy_config[1],proxy_username=proxy_config[2],proxy_password=proxy_config[3])chrome_options.add_extension(proxyauth_plugin_path)return webdriver.Chrome(options=chrome_options)
# 设置代理IP:分别填入代理ip,端口,账号,密码
proxy_config = ["xxx", "xxx", "xxx", "xxx"]driver = configure_headless_browser(proxy_config)
driver.get('http://httpbin.org/ip')time.sleep(3)
driver.quit()
**
终于生效!!!得到了不同的ip地址!
**
参考:https://cloud.tencent.com/developer/article/2376251