使用Selenium通过手机iproxy代理查IP时数据消耗过高问题
降低Selenium代理数据消耗的解决方案
1. 禁用Chrome不必要的资源加载
Selenium默认启动的Chrome会加载所有网页资源(图片、JS、CSS、广告等),而手动浏览时浏览器会自动过滤或缓存部分资源。添加以下启动参数可大幅减少数据消耗:
def get_chromedriver(use_proxy=False, user_agent=None): path = os.path.dirname(os.path.abspath(__file__)) service = Service(executable_path=os.path.join(path, 'chromedriver.exe')) chrome_options = webdriver.ChromeOptions() # 添加资源禁用参数 chrome_options.add_argument('--blink-settings=imagesEnabled=false') # 禁用图片加载 chrome_options.add_argument('--disable-javascript') # 若无需JS可禁用(按需调整) chrome_options.add_argument('--disable-css') # 禁用CSS渲染 chrome_options.add_argument('--disable-plugins') # 禁用插件 chrome_options.add_argument('--disable-background-networking') # 禁用后台网络请求 chrome_options.add_argument('--disable-sync') # 禁用账户同步 chrome_options.add_argument('--no-first-run') # 跳过首次运行初始化 chrome_options.add_argument('--no-default-browser-check') if use_proxy: pluginfile = 'proxy_auth_plugin.zip' with zipfile.ZipFile(pluginfile, 'w') as zp: zp.writestr("manifest.json", manifest_json) zp.writestr("background.js", background_js) chrome_options.add_extension(pluginfile) # 只允许代理插件运行,禁用其他扩展 chrome_options.add_argument(f'--disable-extensions-except={pluginfile}') if user_agent: chrome_options.add_argument('--user-agent=%s' % user_agent) driver = webdriver.Chrome(service=service, options=chrome_options) return driver
2. 优化代理插件的请求拦截范围
原代理插件监听所有URL的认证请求,会产生不必要的拦截和数据交互。缩小监听范围到你实际访问的域名:
修改background_js中的onAuthRequired监听部分:
chrome.webRequest.onAuthRequired.addListener( callbackFn, {urls: ["https://*.google.com/*", "https://httpbin.org/*"]}, // 仅监听目标网站 ['blocking'] );
同时可优化bypassList,排除无需代理的本地域名:
bypassList: ["localhost", "127.0.0.1"]
3. 启用Chrome持久化缓存
Selenium默认使用临时用户目录,每次启动都会重新下载所有资源。指定持久化用户目录,让浏览器缓存资源:
在chrome_options中添加:
chrome_options.add_argument(r'--user-data-dir=C:\selenium_chrome_profile') # 自定义缓存目录路径 chrome_options.add_argument('--disk-cache-size=1073741824') # 设置缓存大小为1GB
4. 代码逻辑优化
- 减少不必要的页面访问:你的代码打开了两个IP查询页面,可合并为一个(比如只访问
https://httpbin.org/ip) - 及时关闭浏览器:操作完成后调用
driver.quit()释放资源,避免后台残留请求
修改main函数:
def main(): driver = get_chromedriver(use_proxy=True) try: driver.get('https://httpbin.org/ip') # 仅访问必要页面 time.sleep(2) # 等待页面加载完成 finally: driver.quit() # 确保关闭浏览器
内容的提问来源于stack exchange,提问作者King
相关产品推荐
相关产品推荐

