一.簡介
以下來自chatGPT回答:
selenium-wire是一個基于selenium的Python庫,它擴展了selenium的功能,使得我們可以在自動化測驗中直接訪問和修改瀏覽器的網路請求和回應,selenium-wire可以攔截和修改HTTP請求和回應,從而可以在測驗程序中模擬 網路環境、除錯和分析網路請求以及實作自定義的網路請求和回應處理邏輯,與selenium自帶的webdriver不同,selenium-wire使用了第三方庫mitmproxy來實作網路請求的攔截和修改,因此,使用selenium-wire需要先安裝mitmproxy,
二.用法
1.安裝selenium-wire庫
pip install selenium-wire
mitmproxy安裝使用可參考:https://www.cnblogs.com/lihongtaoya/p/17446958.html
2.獲取請求資訊
1)獲取所有的請求資訊
get_list = driver.requests # 回傳的是個陣列
當呼叫 driver.requests時,回傳的是當前頁面所有已經請求并回應過了的介面資料,如果某個請求還沒有完成或者被阻塞,那么這個請求對應的資料不會出現在 requests 串列中,
2)獲取請求行/頭/體
for i in get_list: if 'https://www.baidu.com/sugrec' in i.url: print(i.url) # 請求地址 print(i.date) # 請求時間 print(i.method) # 請求方式 print(i.headers) # 請求頭 or i.headers['Content-Type'] print(i.params) # 請求引數 print(i.host) # 請求域名
driver.requests獲取的是當前頁面所有的請求,因此我們在使用時需過濾下自己所要的介面資訊,
3)create_response()方法
for i in get_list: if 'text/html' not in i.response.headers['Content-Type']: # create_response(status_code, headers=(), body=b'') i.create_response(200, [('Content-Type', 'text/plain')], b'["Hello","world"]') # mock介面回應
create_response()為mock介面回應資訊,回傳我們需要的資訊,
4)abort()方法
for i in get_list: if 'text/html' not in i.response.headers['Content-Type']: i.abort(error_code=403) # 中斷請求,并回傳狀態碼403 print(i.response.status_code)
這里需要注意的是3,4方法所可以改變回應資料,但服務端記錄的資料還是實際請求的值,
3.獲取回應資訊
這里直接貼代碼吧,備注很詳細,
for i in get_list: if 'https://www.baidu.com/sugrec' in i.url: print(i.response.date) # 當前回應時間 print(i.response.reason) # 回應狀態 ok or Not found print(i.response.headers['Content-Type']) # 回應的資料型別 print(i.response.status_code) # 回應狀態碼 # 獲取回應的body并轉為json型別輸出 from seleniumwire.utils import decode body = decode(i.response.body, i.response.headers.get('Content-Encoding', 'identity')) decoded_response = body.decode('utf-8') # 將二進制位元組串解碼為 UTF-8 編碼的字串 json_response = json.loads(decoded_response) # 將 JSON 字串轉換為 Python 物件 print(json_response)
4.實體
import json import time from selenium.webdriver.common.by import By from seleniumwire import webdriver driver = webdriver.Chrome() driver.implicitly_wait(10) driver.get("https://www.baidu.com") driver.find_element(By.ID, value='kw').send_keys('豬') driver.find_element(By.ID, value='su').click() time.sleep(5) # 等待5s,讓所有介面請求完 get_list = driver.requests # 獲取當前所有的請求資訊 for i in get_list: if 'https://www.baidu.com/sugrec' in i.url: print(i.response.date) # 當前回應時間 print(i.response.reason) # 回應狀態 ok or Not found print(i.response.headers['Content-Type']) # 回應的資料型別 print(i.response.status_code) # 回應狀態碼 # 獲取回應的body并轉為json型別輸出 from seleniumwire.utils import decode body = decode(i.response.body, i.response.headers.get('Content-Encoding', 'identity')) decoded_response = body.decode('utf-8') # 將二進制位元組串解碼為 UTF-8 編碼的字串 json_response = json.loads(decoded_response) # 將 JSON 字串轉換為 Python 物件 print(json_response) driver.quit()
selenium-wrie官方檔案:https://pypi.org/project/selenium-wire/
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/554798.html
標籤:其他
下一篇:返回列表
