使用Webshare代理+Selenium WebDriver爬取HTTPS页面时遇ERR_TUNNEL_CONNECTION_FAILED错误
排查步骤与解决方案
1. 校验代理信息并处理URL编码
Webshare代理的用户名或密码如果包含@、:、/这类特殊字符,直接拼接会导致代理地址解析错误,必须先做URL编码:
from urllib.parse import quote username = quote("你的Webshare用户名") password = quote("你的Webshare密码") proxy_url = f"http://{username}:{password}@proxyIP:proxyPort"
2. 调整Selenium Wire代理配置
添加SSL验证禁用项,避免证书校验失败导致的连接问题,修改后的配置如下:
options = { 'proxy': { 'http': proxy_url, 'https': proxy_url, 'no_proxy': 'localhost,127.0.0.1', 'verify_ssl': False # 禁用SSL验证,适配Webshare代理环境 } }
3. 清除Chrome代理干扰项
在ChromeOptions中添加参数,避免系统代理或自动配置覆盖Selenium Wire的代理设置:
chrome_options = Options() # 禁用系统代理 chrome_options.add_argument('--no-proxy-server') # 忽略证书错误 chrome_options.add_argument('--ignore-certificate-errors')
4. 先验证代理连通性
在代码外先用curl测试代理是否可用,排除网络或代理本身的问题:
curl -x http://user:pass@proxyIP:proxyPort https://example.com -v
修改后的完整代码
from seleniumwire import webdriver from selenium.webdriver.chrome.service import Service from selenium.webdriver.chrome.options import Options from urllib.parse import quote # 处理代理用户名密码的URL编码 username = quote("你的Webshare用户名") password = quote("你的Webshare密码") proxy_url = f"http://{username}:{password}@proxyIP:proxyPort" options = { 'proxy': { 'http': proxy_url, 'https': proxy_url, 'no_proxy': 'localhost,127.0.0.1', 'verify_ssl': False } } chrome_driver_path = "C:\\Program Files (x86)\\chromedriver.exe" service = Service(chrome_driver_path) chrome_options = Options() # 添加Chrome参数 chrome_options.add_argument('--no-proxy-server') chrome_options.add_argument('--ignore-certificate-errors') driver = webdriver.Chrome(service=service, options=chrome_options, seleniumwire_options=options) try: driver.get('https://example.com') driver.implicitly_wait(8) print("页面加载成功") finally: driver.quit()
内容的提问来源于stack exchange,提问作者Joshua Petersen
相关产品推荐
相关产品推荐

