// 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();
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
要在页面加载完成之前仅获取网络日志(在页面的主要使用过程中没有ajax/async网络日志),可以获取性能日志:http://chromedriver.chromium.org/logging/performance-log
例如,要启用ChromeDriver的性能日志记录
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
一旦有了HAR文件,它就是一个类似JSON的网络事件列表,您可以使用它。
使用Python和ChromeDriver
要获取网络日志,需要在python中安装BrowserMobProxy和selenium
你需要启动浏览器代理并配置chrome驱动程序的chrome代理选项
然后可以使用selenium导航到页面
导航之后,您可以从代理服务器获取json格式的网络日志
在退出驱动程序之前,也要在最后停止代理服务器
相关问题 更多 >
编程相关推荐