为什么要用 selenium-wire
因为测试环境部署的改变: 以前是 hosts 或多个代理切换,现在是单个代理 + 指定环境的请求头来决定对应的测试环境(nohosts)。
那么 selenium 需要能修改请求头:
Google 搜 “selenium modify headers” 找到了 selenium-wire,它提供修改请求头(或响应头)的方法
selenium-wire 替换 selenium 处理
- 安装(要求:Python 3.6+,Selenium 3.4.0+)
pip install selenium-wire
selenium-wire 的 webdriver 是原 selenium 的封装,脚本类不要改,需要调整的地方如下。文章源自玩技e族-https://www.playezu.com/191294.html
- 引入 webdriver 需要修改
from seleniumwire import webdriver
- 定义 driver 的地方提供的特殊的参数 seleniumwire_options,如 chrome 设置代理也是通过这个参数
wireOptions={
'proxy': {
'http': 'http://127.0.0.1:8888',
'https': 'http://127.0.0.1:8888',
'no_proxy': 'localhost,127.0.0.1'
}
}
if chromeOptions is not None:
for option in chromeOptions:
chrome_options.add_argument(option)
chrome_options.add_experimental_option("excludeSwitches", ["enable-automation"])
chrome_options.add_experimental_option("useAutomationExtension", False)
driver = webdriver.Chrome(executable_path=ChromeDriverPath,options=chrome_options,seleniumwire_options=wireOptions)
selenium-wire 的几个用法举例
添加/修改请求头
方法 1:全局性的添加请求头/响应头文章源自玩技e族-https://www.playezu.com/191294.html
driver.header_overrides=[ ('.*pay.xxxx.com.*', {"Proxy-Client-Ip":"67.220.90.13"}) ] # 设置匹配域名的请求头 driver.header_overrides={"Proxy-Client-Ip":"67.220.90.13"} # 设置全局的请求头
方法 2:利用 request 添加修改请求头/响应头文章源自玩技e族-https://www.playezu.com/191294.html
def interceptor(request):
if request.host=='pay.xxxx.com':
del request.headers['Referer']
request.headers['Referer'] = 'some_referer'
driver.request_interceptor = interceptor
driver.get(...)
阻止部分请求 -- 解决网页加载速度受一些埋点 js 影响的问题
def interceptor(request:Request):
p=re.compile(".*(riskified|google|doubleclick|snapengage.com|taboola|hubapi|hubspot|facebook).*")
if p.findall(request.host):
request.abort()
driver.request_interceptor = interceptor
- 如果想恢复,可以删除
del driver.request_interceptor
del driver.header_overrides
selenium-wire 的更多用法
可以修改响应头、内容,可以获取请求和相应的信息.....
具体见:https://github.com/wkeeling/selenium-wire文章源自玩技e族-https://www.playezu.com/191294.html
软件测试视频文章源自玩技e族-https://www.playezu.com/191294.html 文章源自玩技e族-https://www.playezu.com/191294.html