我一直在尝试将 BrowserMob 集成到我的 selenium 测试中。它适用于在 http 上运行的网站,但对于 https 网站,浏览器将停止工作,并且 HAR 文件不包含任何请求。
导航到 https 站点时,我在浏览器上收到此错误。
“代理服务器有问题或地址不正确。”
这是我的代码。
public class Browsermob {
BrowserMobProxy proxy = new BrowserMobProxyServer();
@Test
public void browsermobtest() {
proxy.start(9091);
// 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);
System.setProperty("webdriver.chrome.driver", "C:/Users/Madis/Documents/chromedriver.exe");
WebDriver driver = new ChromeDriver(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 "google.com"
proxy.newHar("http://www.google.com/");
// open google.com
driver.get("https://www.google.ee/#gfe_rd=cr");
driver.findElement(By.cssSelector("#gb_70")).click();
}
@AfterMethod
public void Afterthetest() {
// get the HAR data
Har har = proxy.getHar();
File harFile = new File("C:/Users/Madis/Documents/har.har");
try {
har.writeTo(harFile);
} catch (IOException e) {
e.printStackTrace();
}
}
}
最佳答案
您不需要在 Selenium 代理对象上指定 sslProxy。 ClientUtil.createSeleniumProxy 会为您完成此操作,并且在大多数简单情况下,它会选择合适的默认值(使用 InetAddress.getLocalHost();如果这适用于 HTTP,那么它也会起作用也适用于 HTTPS)。
需要记住的一些事情:
- 您将在浏览器中收到 SSL 警告,除非您告诉浏览器忽略证书错误(在 Chrome 上,使用 --ignore-certificate-errors 命令行标志),或者安装 BMP CA位于浏览器的信任存储区中(对于 Windows 上的 Chrome,您必须将其安装在 Windows 信任存储区中)。
- 根据您的 Chrome 和操作系统版本,您可能需要使用命令行选项指定备用用户数据目录。例如,
--user-data-dir=/tmp/insecurechrome
。 - BMP 有自己的受信任证书来源(Java 信任存储 + Mozilla 的最新列表),因此,如果您尝试使用私有(private) CA 颁发的证书连接到内部网站,则需要告诉 BMP 信任其中一个私有(private) CA 或使用 .setTrustAllServers(true) 跳过证书验证。
- 在调用 createSeleniumProxy() 之前,必须使用 .start(...) 启动代理。
结合所有这些内容,您的代码将如下所示:
BrowserMobProxy proxy = new BrowserMobProxyServer();
proxy.setTrustAllServers(true);
proxy.start(9091);
// get the Selenium proxy object
Proxy seleniumProxy = ClientUtil.createSeleniumProxy(proxy);
// NOTE: there is no call to .setSslProxy() here
// configure it as a desired capability
DesiredCapabilities capabilities = new DesiredCapabilities();
capabilities.setCapability(CapabilityType.PROXY, seleniumProxy);
System.setProperty("webdriver.chrome.driver", "C:/Users/Madis/Documents/chromedriver.exe");
ChromeOptions options = new ChromeOptions();
options.addArgument("--ignore-certificate-errors");
// replace 'somedirectory' with a suitable temp dir on your filesystem
options.addArgument("--user-data-dir=somedirectory");
capabilities.setCapability(ChromeOptions.CAPABILITY, options);
WebDriver driver = new ChromeDriver(capabilities);
// [...]
关于java - Selenium (Chrome) 和 BrowserMob 不适用于 https,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39348289/