selenium中獲取http請求/返回

我們在使用selenium做UI自動化時,很多情況下定位問題困難,請求的唯一ID是什麼?當時請求出錯了返回的是什麼?怎麼定位?

光UI截圖還是有點不直觀,有時候我們會想怎麼獲取請求或返回response?

 

一、selenium自身不支持

 首先在selenium源生的API支已經表明不支持了,github上也說明了,以後也不會加了

  

 

 

 google上討論的鏈接:https://code.google.com/p/selenium/issues/detail?id=141

 

二、解決方案

這時我們可以換個思路來思考,瀏覽器都有F12的功能,我們能不能通過這個方式來獲取內容。看看解決方法:

Java版本:

LoggingPreferences logPrefs = new LoggingPreferences();
logPrefs.enable(LogType.PERFORMANCE, Level.ALL);
cap.setCapability(CapabilityType.LOGGING_PREFS, logPrefs);

LogEntries logs = driver.manage().logs().get("performance");

Python版本:

from selenium import webdriver
from selenium.webdriver.common.desired_capabilities import DesiredCapabilities

ca = DesiredCapabilities.CHROME
ca["goog:loggingPrefs"] = {"performance": "ALL"}
driver = webdriver.Chrome(desired_capabilities=ca)
driver.get("http://xxx")
logs = driver.get_log("performance")
print(logs)

這時,你會看到所有的請求,及返回內容,包括header

 

三、其它方案:

網上還有其它的方法。下面這裏給鏈接,就不詳細說明了:

1、selenium-wire  方法。具體可以看pypi的文檔。有個不便處就是。log全打出來了

2、Browser-Mob  方法。建立代理的一個類似方案。需要安裝java及啓動proxy

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章