如何使用python硒获取浏览器网络日志 [英] How to get browser network logs using python selenium
问题描述
我正在尝试使用硒来获取浏览器网络日志以调试请求/响应.您能帮我找出办法吗?
I'm trying to get browser network logs using selenium to debug request/responses. Could you please help me to find out a way.
我正在使用硒3.14.0和最新的Chrome浏览器.
And I'm using selenium 3.14.0 and latest Chrome browser.
推荐答案
使用Python和ChromeDriver
要获取网络日志,您需要安装 BrowserMobProxy 以及硒python
To get network logs, you need to install BrowserMobProxy as well along with selenium in python
pip install browsermob-proxy
您需要启动浏览器代理并在chrome驱动程序的chrome选项中配置代理,
You need to start browser proxy and configure the proxy in chrome option of chrome driver,
from browsermobproxy import Server
from selenium import webdriver
server = Server("path/to/browsermob-proxy")
server.start()
proxy = server.create_proxy()
# Configure the browser proxy in chrome options
chrome_options = webdriver.ChromeOptions()
chrome_options.add_argument("--proxy-server={0}".format(proxy.proxy))
browser = webdriver.Chrome(chrome_options = chrome_options)
#tag the har(network logs) with a name
proxy.new_har("google")
然后您可以使用硒导航到页面
Then you can navigate to page using selenium
browser.get("http://www.google.co.in")
导航后,您可以从代理获取json格式的网络日志
After navigation, you can get the network logs in json format from the proxy
print(proxy.har) # returns a Network logs (HAR) as JSON
在退出驱动程序之前,还要在最后停止代理服务器,
Also before quitting the driver, stop the proxy server as well at the end,
server.stop()
browser.quit()
这篇关于如何使用python硒获取浏览器网络日志的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!