如何在Selenium Python中使用代理?求助代码实现问题
为SeleniumWire配置代理的解决方案
首先,你的代码存在重复导入问题——同时导入了selenium.webdriver和seleniumwire.webdriver,后者会覆盖前者,只需保留seleniumwire的导入即可,它兼容原生Selenium的所有功能。
下面分两种常见代理场景给出实现代码:
1. 无认证的HTTP/HTTPS代理
直接在初始化webdriver.Chrome时通过seleniumwire_options传入代理配置:
from seleniumwire import webdriver from selenium.webdriver.chrome.service import Service as ChromeService from webdriver_manager.chrome import ChromeDriverManager from varNames import * from disc import * from functions import * from time import sleep # 补充sleep的依赖导入 # 代理配置 proxy_options = { 'proxy': { 'http': 'http://你的代理地址:端口', 'https': 'https://你的代理地址:端口', 'no_proxy': 'localhost,127.0.0.1' # 无需走代理的本地地址 } } # 初始化带代理的浏览器实例 driver = webdriver.Chrome( service=ChromeService(ChromeDriverManager().install()), seleniumwire_options=proxy_options ) driver.get("你的目标URL") # 执行登录流程 sleep(10) login(email_input, password_input, driver) driver.quit()
2. 带用户名密码认证的代理
如果代理需要账号密码验证,在配置中加入认证信息即可:
from seleniumwire import webdriver from selenium.webdriver.chrome.service import Service as ChromeService from webdriver_manager.chrome import ChromeDriverManager from varNames import * from disc import * from functions import * from time import sleep # 带认证的代理配置 proxy_options = { 'proxy': { 'http': 'http://用户名:密码@你的代理地址:端口', 'https': 'https://用户名:密码@你的代理地址:端口', 'no_proxy': 'localhost,127.0.0.1' } } driver = webdriver.Chrome( service=ChromeService(ChromeDriverManager().install()), seleniumwire_options=proxy_options ) driver.get("你的目标URL") sleep(10) login(email_input, password_input, driver) driver.quit()
额外注意事项
- 确保代理地址和端口可正常连通,可提前用浏览器或curl工具测试代理有效性
- 如果使用SOCKS5代理,只需将
http/https前缀替换为socks5://即可 - 你的代码中使用了
sleep但未导入time模块,需补充对应导入语句
内容的提问来源于stack exchange,提问作者TS8k
相关产品推荐
相关产品推荐

