有的時候要獲取網站的上顯示一些信息,如招聘網站在招聘的公司需要的崗位,公司的名稱,公司的地址,但一個個崗位點進去拿公司的地址,加載時間太長
通過抓包發現具體的信息在某一個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))