如何使用python selenium获取浏览器网络日志

2024-06-28 10:52:19 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试使用selenium来调试请求/响应来获取浏览器网络日志。你能帮我找出一条路吗。

我正在使用selenium 3.14.0和最新的Chrome浏览器。


Tags: selenium浏览器chrome网络日志
2条回答

要在页面加载完成之前仅获取网络日志(在页面的主要使用过程中没有ajax/async网络日志),可以获取性能日志:http://chromedriver.chromium.org/logging/performance-log

例如,要启用ChromeDriver的性能日志记录

DesiredCapabilities cap = DesiredCapabilities.chrome();
LoggingPreferences logPrefs = new LoggingPreferences();
logPrefs.enable(LogType.PERFORMANCE, Level.ALL);
cap.setCapability(CapabilityType.LOGGING_PREFS, logPrefs);
RemoteWebDriver driver = new RemoteWebDriver(new URL("http://127.0.0.1:9515"), cap);

chromium performance-log page还链接到这个完整的示例https://gist.github.com/klepikov/5457750,该示例有Java和python代码来获取性能日志。

同样,重要的是要记住,这只会让网络请求直到页面加载完成。之后,驱动程序将只返回相同的性能日志,直到页面重新加载。


如果希望在整个页面使用过程中异步获取网络日志,可以使用BrowserMobProxy充当Selenium驱动程序的代理服务器并捕获所有这些网络请求。然后,您可以从BrowserMobProxy生成的HAR文件中获取捕获的请求:https://github.com/lightbody/browsermob-proxy#using-with-selenium

// start the proxy
BrowserMobProxy proxy = new BrowserMobProxyServer();
proxy.start(0);

// get the Selenium proxy object
Proxy seleniumProxy = ClientUtil.createSeleniumProxy(proxy);

// configure it as a desired capability
DesiredCapabilities capabilities = new DesiredCapabilities();
capabilities.setCapability(CapabilityType.PROXY, seleniumProxy);

// start the browser up
WebDriver driver = new FirefoxDriver(capabilities);

// enable more detailed HAR capture, if desired (see CaptureType for the complete list)
proxy.enableHarCaptureTypes(CaptureType.REQUEST_CONTENT, CaptureType.RESPONSE_CONTENT);

// create a new HAR with the label "yahoo.com"
proxy.newHar("yahoo.com");

// open yahoo.com
driver.get("http://yahoo.com");

// get the HAR data
Har har = proxy.getHar();

一旦有了HAR文件,它就是一个类似JSON的网络事件列表,您可以使用它。

使用Python和ChromeDriver

要获取网络日志,需要在python中安装BrowserMobProxy和selenium

pip install browsermob-proxy

你需要启动浏览器代理并配置chrome驱动程序的chrome代理选项

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")

然后可以使用selenium导航到页面

driver.get("http://www.google.co.in")

导航之后,您可以从代理服务器获取json格式的网络日志

print(proxy.har) # returns a Network logs (HAR) as JSON 

在退出驱动程序之前,也要在最后停止代理服务器

server.stop()
browser.quit()

相关问题 更多 >