我创建了从 Chrome 获取网络流量的简单方法:
public void saveNetworkTraffic() {
System.setProperty("webdriver.chrome.driver", System.getProperty("user.dir") + "/bin/chromedriver");
String sFileName = "networklog.xar";
BrowserMobProxy proxy = new BrowserMobProxyServer();
proxy.start(0);
Proxy seleniumProxy = ClientUtil.createSeleniumProxy(proxy);
DesiredCapabilities capabilities = new DesiredCapabilities();
capabilities.setCapability(CapabilityType.PROXY, seleniumProxy);
WebDriver driver = new ChromeDriver(capabilities);
WebDriverRunner.setWebDriver(driver);
proxy.enableHarCaptureTypes(CaptureType.REQUEST_CONTENT, CaptureType.RESPONSE_CONTENT);
proxy.newHar("google.com");
driver.get("http://google.com/");
Har har = proxy.getHar();
File harFile = new File(sFileName);
try {
har.writeTo(harFile);
} catch (IOException ex) {
System.out.println(ex.toString());
System.out.println("Could not find file " + sFileName);
}
}
当浏览器打开一个页面时,它会在这一步显示错误“ERR_EMPTY_RESPONSE”,driver.get("http://google.com/")
而不是 Chrome 中通常的谷歌页面。我试图找出错误的原因,但根据https://github.com/lightbody/browsermob-proxy#using-with-selenium,我的代码应该可以正常工作。