使用selenium wire获取浏览器运行时发出的请求-自动化测试
更新时间:2022-06-08 09:18:18 作者:多测师 浏览:154
有的时候要获取网站的上显示一些信息,如招聘网站在招聘的公司需要的岗位,公司的名称,公司的地址,但一个个岗位点进去拿公司的地址,加载时间太长。
通过抓包发现具体的信息在某一个ajax请求里面已经全返回出来了,在页面只显示了一小部分。或者某个网站登录之后需要某个token去调api。
这个时候就可以使用selenium wire,直接拿取某个请求返回的数据,或传入的参数。
1.环境要求
·Python 3.6 +
· Selenium 3.4.0 +
2.安装
pip install selenium-wire
3.示例
from seleniumwire import webdriver
driver = webdriver.Chrome()
driver.get('https://www.baidu.com')
# 通过requests属性访问请求
for request in driver.requests:
if request.response:
print("Url:", request.url)
print("Code:", request.response.status_code)
print("Content-Type:", request.response.headers['Content-Type'])
4.拦截器
可以在某些请求发出前,修改请求的参数或直接阻止请求。
import json
from seleniumwire import webdriver
# 设置拦截器
def interceptor(request):
# 拦截.png,.jpg,.gif结尾的请求
if request.path.endswith(('.png', '.jpg', '.gif')):
request.abort()
driver = webdriver.Chrome()
driver.request_interceptor = interceptor
driver.get('https://www.baidu.com')
# 通过requests属性访问请求
for request in driver.requests:
if request.response:
print("Url:", request.url)
print("Code:", request.response.status_code)
print("Content-Type:", request.response.headers['Content-Type'])
5.添加和修改请求参数
# 设置拦截器
def interceptor(request):
# 添加请求参数
params = request.params
params['foo'] = 'bar'
request.params = params
# 修改POST请求正文中的JSON
if request.method == 'POST' and request.headers['Content-Type'] == 'application/json':
# 获取原请求内容
body = request.body.decode('utf-8')
data = json.loads(body)
# 修改要改变的参数
data['foo'] = 'bar'
# 将修改好的参数设置回请求
request.body = json.dumps(data).encode('utf-8')
# 更新内容长度
del request.headers['Content-Length']
request.headers['Content-Length'] = str(len(request.body))
以上内容为大家介绍了自动化测试中的使用selenium wire获取浏览器运行时发出的请求,本文由多测师亲自撰写,希望对大家有所帮助。了解更多自动化测试相关知识:https://www.aichudan.com/xwzx/