Selenium Wire编辑header破解反爬机制和访问限制

一、selenium Wire介绍

  • 介绍
    Selenium Wire扩展了Selenium的Python绑定,使您能够访问浏览器发出的底层请求。您已使用Selenium相同的方式编写代码,但是您获得了额外的api,用于检查请求和响应,并动态地对它们进行更改。(注:意思是这个不仅包含了selenium的功能,还额外增加了新的扩展功能,引用seleniumwire后就不用再引用selenium)

  • 工作原理
      Selenium Wire的工作原理是将浏览器流量重定向到它在后台运行的内部代理服务器。当请求流经代理服务器时,它们被拦截和捕获。捕获请求可能会使事情变慢,但你可以做一些事情来限制被捕获的内容。

二、selenium Wire安装

安装selenium-wire需要先安装mitmproxy

  • 安装mitmproxy
pip install -i https://pypi.tuna.tsinghua.edu.cn/simple mitmproxy
  • 安装selenium-wire
pip install -i https://pypi.tuna.tsinghua.edu.cn/simple selenium-wire

三、selenium Wire使用实例

本次实例中访问站点次数过多或频率过快时会弹窗提示并结束自动化测试运行程序,增加等待时长不能解决该问题,与开发沟通后得到解决方案是在header里增加参数键值对test:test则能够忽略限制(不同项目的破解值不一样,仅作样例参考),查找资料决定使用selenium Wire来增加header参数,成功解除访问限制。
Selenium Wire编辑header破解反爬机制和访问限制_第1张图片

from seleniumwire import webdriver
from selenium.webdriver.common.desired_capabilities import DesiredCapabilities

chrome_options = webdriver.ChromeOptions()
chrome_options.add_experimental_option('w3c', False)
caps = DesiredCapabilities.CHROME
# 打开chrome浏览器
# 此步骤很重要,设置为开发者模式,防止被各大网站识别出来使用了Selenium
# chrome_options.add_experimental_option('excludeSwitches', ['enable-logging'])  # 禁止打印日志
chrome_options.add_experimental_option('excludeSwitches', ['enable-automation'])  # 跟上面只能选一个
# chrome_options.add_argument('--headless')  # 无头模式,打开后后台运行浏览器,不在电脑显示
chrome_options.add_argument('--disable-gpu')  # 上面代码就是为了将Chrome不弹出界面
chrome_options.add_argument('--start-maximized')  # 最大化
chrome_options.add_argument('--incognito')  # 无痕隐身模式
chrome_options.add_argument("disable-cache")  # 禁用缓存
chrome_options.add_argument('disable-infobars')
chrome_options.add_argument('log-level=3')  # INFO = 0 WARNING = 1 LOG_ERROR = 2 LOG_FATAL = 3 default is 0


# header新增参数test解除访问拦截
def interceptor(request):
    request.headers['test'] = 'test'


caps['loggingPrefs'] = {'performance': 'ALL'}
driver = webdriver.Chrome(desired_capabilities=caps, options=chrome_options)
driver.request_interceptor = interceptor

四、遇到的问题

首次运行过程中报错ImportError: cannot import name ‘EdgeOptions’,解决方法去webdriver文件里把EdgeOptions这行注释掉
Selenium Wire编辑header破解反爬机制和访问限制_第2张图片

Selenium Wire编辑header破解反爬机制和访问限制_第3张图片
参考文档:
selenium-wire简介
Python |Selenium Wire 扩展Selenium的Python绑定,使您能够检查浏览器发出的请求
用Selenium给chrome添加任意请求头信息

你可能感兴趣的:(软件测试,selenium,selenium,测试工具)