实例1:
import time
from seleniumwire import webdriver
# Create a new instance of the Chrome driver
driver = webdriver.Chrome()
# Go to the YouTube homepage.
driver.get('http://tool.liumingye.cn/music/?page=audioPage&type=migu&name=%E6%8A%96%E9%9F%B3')
time.sleep(5)
# Access requests via the `requests` attribute
for request in driver.requests:
if request.response:
if request.path == "/m/api/search":
print(request.response.body.decode("utf-8"))
driver.quit()
封装后的driver会有requests这样一个对象,可以发跟浏览器开发者工具的Network进行类比,请求的返回值存储在response.body中。
通过request.path过滤出我们想要的请求,然后获取response.body即可。
实例2:
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'])
实例3:设置拦截器
可以在某些请求发出前,修改请求的参数或直接阻止请求:
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'])