python selenium禁止加载某些请求的实现

来自:网络
时间:2022-01-08
阅读:
目录

问题描述

通过selenium请求目标网站时候, 真实数据(我这里是验证码图片)已经加载出来, 由于网站做了第三方上报所以得等待很久, 但是上报这个请求不是必须的.

例如

验证码已经加载完成, 但是huatuo.qq.com响应时间过长 , webdriver.get()的机制是等待请求的url响应全部完成才进行下一步. 显示等待和隐式等待的作用是每隔多少秒来检测一下这个地址是否加载完成, 所以此处不生效.

那我要做的是: 当请求目标url时候, 希望webdriver不上报或者屏蔽huatuo.qq.com…这样就能节省大量时间, 从而进行下一步操作

python selenium禁止加载某些请求的实现

解决方案

在通过selenium打开目标url后, 植入js插件, 通过插件来屏蔽上报url

配置selenium属性, 添加屏蔽规则

chrome_options.add_argument('--host-resolver-rules=MAP report.huatuo.qq.com 127.0.0.1')

最终效果

python selenium禁止加载某些请求的实现

这样就能专注于目标url, 更快的执行下一步.

其他属性配置

options.add_argument(‘headless') # 无头模式
options.add_argument(‘window-size={}x{}'.format(width, height)) # 直接配置大小和set_window_size一样
options.add_argument(‘disable-gpu') # 禁用GPU加速
options.add_argument(‘proxy-server={}'.format(self.proxy_server)) # 配置代理
options.add_argument('–no-sandbox') # 沙盒模式运行
options.add_argument('–disable-setuid-sandbox') # 禁用沙盒
options.add_argument('–disable-dev-shm-usage') # 大量渲染时候写入/tmp而非/dev/shm
options.add_argument('–user-data-dir={profile_path}'.format(profile_path)) # 用户数据存入指定文件
options.add_argument('no-default-browser-check) # 不做浏览器默认检查
options.add_argument("–disable-popup-blocking") # 允许弹窗
options.add_argument("–disable-extensions") # 禁用扩展
options.add_argument("–ignore-certificate-errors") # 忽略不信任证书
options.add_argument("–no-first-run") # 初始化时为空白页面
options.add_argument('–start-maximized') # 最大化启动
options.add_argument('–disable-notifications') # 禁用通知警告
options.add_argument('–enable-automation') # 通知(通知用户其浏览器正由自动化测试控制)
options.add_argument('–disable-xss-auditor') # 禁止xss防护
options.add_argument('–disable-web-security') # 关闭安全策略
options.add_argument('–allow-running-insecure-content') # 允许运行不安全的内容
options.add_argument('–disable-webgl') # 禁用webgl
options.add_argument('–homedir={}') # 指定主目录存放位置
options.add_argument('–disk-cache-dir={临时文件目录}') # 指定临时文件目录
options.add_argument(‘disable-cache') # 禁用缓存
options.add_argument(‘excludeSwitches', [‘enable-automation']) # 开发者模式

参考

其他详细配置 请点击

返回顶部
顶部