I have been trying to integrate BrowserMob to my selenium tests. It works fine with website that work on http, but with https websites the browsers stop working and the HAR file doesn't contain any requests.
When navigating to a https site I get this error on the browser.
"There is something wrong with the proxy server or the address is incorrect."
Here is my code.
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();
}
}
}
You don't need to specify the sslProxy on the Selenium Proxy object. ClientUtil.createSeleniumProxy does this for you, and in most simple cases it chooses a suitable default value (using InetAddress.getLocalHost(); if that's working for HTTP, it will work for HTTPS as well).
A few things to keep in mind:
You'll receive SSL warnings in the browser unless you either tell the browser to ignore cert errors (on Chrome, use the --ignore-certificate-errors command-line flag), or install the BMP CA in the browser's trust store (for Chrome on Windows, you must install it in the Windows trust store).
Depending on your version of Chrome and OS, you may need to specify an alternate user-data-dir using a command line option. For example, --user-data-dir=/tmp/insecurechrome.
BMP has its own source of trusted certificates (Java trust store + a recent list from Mozilla), so if you're trying to connect to internal websites with certificates issued by a private CA, you need to tell BMP to either trust the private CA or skip certificate validation using .setTrustAllServers(true).
The proxy must be started using .start(...) before calling createSeleniumProxy().
Combining all these things, your code would look something like this:
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);
// [...]
I had this problem. After numerous trials, I got to know we have to add setmitmManager and upstream proxy if you are connected to corporate proxy. It worked for me.
Here is the example code.
BrowserMobProxy proxy = new BrowserMobProxyServer();
proxy.setTrustAllServers(true);
//Add below line if you are under corporate proxy.
proxy.setChainedProxy(new InetSocketAddress("XXX.XXX.com", 8080));
proxy.setMitmManager(ImpersonatingMitmManager.builder().trustAllServers(true).build());
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);
// your code to start, get har
You're confusing the browser mob proxy object and the selenium proxy object.
Your proxy variable proxy is the actual proxy which your browser will connect to.
Your seleniumProxy variable is an object which represents your browser's proxy settings.
You are telling your browser to use "trustAllSSLCertificates" as the address for your proxy server, which is why you are getting an error. Instead, you should tell browsermob (proxy) to trustAllSSLCertificates, and your sslProxy needs to reference your browsermob proxy.
Start the proxy like so:
public void startProxy() {
proxy = new BrowserMobProxyServer();
proxy.setTrustAllServers(true);
proxy.start(9091);
}
Start the driver like so:
public void startBrowserWithProxy() {
Proxy seleniumProxy = ClientUtil.createSeleniumProxy(proxy);
seleniumProxy.setSslProxy("localhost:" + proxy.getPort());
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);
}
I managed to get it to work. After adding log4j and debugging the browsermob logs the issue was caused by
Caught an exception on ClientToProxyConnection
java.lang.NoSuchMethodError: com.google.common.net.HostAndPort.fromHost(Ljava/lang/String;)Lcom/google/common/net/HostAndPort;
In order to make it to work I had to add a dependency to my maven project. This fixed this issue and I was able to see the capture the traffic on https sites aswell http sites.
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
<version>20.0</version>
</dependency>
I hade a lot for capabilities, options and etc but it did not work
In my case, I changed exist dependency in pom
<artifactId>browsermob-core-littleproxy</artifactId>
to
<dependency>
<groupId>net.lightbody.bmp</groupId>
<artifactId>browsermob-core</artifactId>
<version>2.1.5</version>
</dependency>
and up "guava" version.
After that everything became good
Related
I am learning selenium testing and have encountered my first problem after few hours :D
Objective: add a proxy into my selenium program so that it will not access the internet straight from my router.
(Proxy- running tor browser on localhost. Works with other web scrapers smoothly)
The problem is, it seems like program does not see proxy settings or goes around it. Navigating program to "check ip" websites shows original ip, not changed one by proxy.
My code: [as in documentation https://www.selenium.dev/documentation/webdriver/http_proxies/]
Proxy proxy = new Proxy();
proxy.setHttpProxy("127.0.0.1:9150");
ChromeOptions options = new ChromeOptions();
options.setCapability("proxy", proxy);
Then I tried several other approaches found online (including a deprecated one)
/*String proxy = "127.0.0.1:9150";
ChromeOptions options = new ChromeOptions().addArguments("--proxy-server=http://" +proxy);
*/
/*String proxy = "localhost:9150";
Proxy p = new Proxy();
p.setHttpProxy(proxy);
DesiredCapabilities cap = new DesiredCapabilities();
cap.setCapability(CapabilityType.PROXY, p);
*/
and then it goes into driver parameter (commented ones are using options and cap)
WebDriver driver = new ChromeDriver(options);
Using the documentation code I do not get any error. It just does not change ip.
I tried everything I could think of but without success.
Notes:
ip & port are correct
websites are accessed after setting up proxy.
using commented code (first block, two lines) returns "This site can’t be reached" in chrome and " org.openqa.selenium.WebDriverException: unknown error: net::ERR_TUNNEL_CONNECTION_FAILED" in console
same code as note 3) but protocol changed to https "...https://" +proxy);" returns "No internet" in browser and "org.openqa.selenium.WebDriverException: unknown error: net::ERR_PROXY_CONNECTION_FAILED" in console
Your troubleshooting, may have highlighted the cause. 3) shows that it could not create the tunnel with your proxy using http. 4) shows tunnel created using https, but proxy connection failed. So it is probably looking for some type of creds.
Update your code to add SSL proxy:
Proxy proxy = new Proxy();
proxy.setHttpProxy("127.0.0.1:9150");
proxy.setSslProxy("127.0.0.1:9150");
ChromeOptions options = new ChromeOptions();
options.setCapability("proxy", proxy);
I use selenium for end-to-end test with chromeDriver. The websites to test require an ssl certificate. When I manually open the browser, there is a popup that lets me select an installed certificate. Different tests access different URLs and also need different certificates. However, if I run the tests in headless mode, there is no popup. So I need a way to programatically set a certificate (eg. set a .pem file) to be used for the current test.
How can I achieve this?
I tried setting up a browserMob proxy which I then configured as a proxy in selenium - however, this does not seem to do anything... Are there better approaches? What am I doing wrong? Here's what I tried:
PemFileCertificateSource pemFileCertificateSource = new PemFileCertificateSource(
new File("myCertificate.pem"),
new File("myPrivateKey.pem"),
"myPrivateKeyPassword");
ImpersonatingMitmManager mitmManager = ImpersonatingMitmManager.builder()
.rootCertificateSource(pemFileCertificateSource)
.build();
BrowserMobProxy browserMobProxy = new BrowserMobProxyServer();
browserMobProxy.setTrustAllServers(true);
browserMobProxy.setMitmManager(mitmManager);
browserMobProxy.start(8080);
ChromeOptions chromeOptions = new ChromeOptions();
chromeOptions.setProxy(ClientUtil.createSeleniumProxy(browserMobProxy));
WebDriver webDriver = new ChromeDriver(chromeOptions);
// use the webdriver for tests, e.g. assertEquals("foo", webDriver.findElement(...))
So apparantly this is not possible with BrowserMob out of the box. I therefore wrote a proxy extension SeleniumSslProxy that can be plugged into Selenium and adds certificate based authentication to create a HTTPS connection.
This is how it works:
intercept Selenium HTTP requests with BrowserMob
setup an SSLContext given a certificate (.pfx file) and password
use okhttp to forward the request to the target URL
convert the okhttp Response to a netty FullHttpResponse so it can be handled by Selenium
You can find the code on github. Here's an example how it can be used in Selenium end-to-end tests (also works in headless mode):
#Before
public void setup() {
ClassLoader classLoader = ClassLoader.getSystemClassLoader();
File clientSslCertificate = new File(
classLoader.getResource("certificates/some-certificate.pfx").getFile());
String certificatePassword = "superSecret";
this.proxy = new SeleniumSslProxy(clientSslCertificate, certificatePassword);
this.proxy.start();
ChromeOptions chromeOptions = new ChromeOptions();
chromeOptions.setProxy(proxy);
this.webDriver = new ChromeDriver(chromeOptions);
}
#Test
public void pageTitleIsFoo() {
// given
String url = "http://myurl.lol";
// NOTE: do not use https in the URL here. It will be converted to https by the proxy.
// when
this.webDriver.get(url);
this.webDriver.manage().timeouts().implicitlyWait(5, SECONDS);
// then
WebElement title = this.webDriver.findElement(By.className("title"));
assertEquals("Foo", title.getText());
}
#After
public void teardown() {
this.webDriver.quit();
this.proxy.stop();
}
Note that I only used chromeDriver and never tested it with other drivers. Minor adjustments to the SeleniumSslProxy might be necessary to be used with other drivers.
Proxy not working in Selenium
First of all i use free proxys from proxyfish (maybe thats the problem alrdy) https://hidemyna.me/en/proxy-checker/ tells me theyre working.
I found lots of code/solutions, most is outdated (capabilities=options..) or not working for me.
Tried several code/proxys chrome/ff however https://www.iplocation.net/ and https://whatismyipaddress.com showing actual IP address (IPv4 and IPv6).
What I tried..
System.setProperty("webdriver.chrome.driver", "C:\\selenium\\chromedriver.exe");
System.getProperties().put("74.208.112.***", "8080"); //1st try
Proxy proxy = new Proxy();
proxy.setHttpProxy("74.208.112.***:8080"); //2nd try
ChromeOptions options = new ChromeOptions();
options.setCapability("proxy", proxy);
options.setProxy(proxy);
options.addArguments("--proxy-server=74.208.112.***:8080"); //3rd try
ChromeDriver driver = new ChromeDriver(options);
driver.get("https://www.iplocation.net/");
driver.get("https://whatismyipaddress.com/");
Solution:
proxy.setSslProxy("74.208.112.***:8080");
Is there a way to test proxy connection before using proxy?
I am trying to intercept the requests made by Webdriver using BrowserMobProxy.
But the below code is not working..It is not able to open the site google.com.
It says the "Internet Explorer cannot open the site"
proxyServer = new ProxyServer(9101);
proxyServer.start();
proxyServer.setCaptureHeaders(true);
proxyServer.setCaptureContent(true);
proxyServer.addRequestInterceptor(new RequestInterceptor() {
#Override
public void process(BrowserMobHttpRequest request, Har har) {
System.out.println("From Process method");
}
});
seleniumProxy = proxy.seleniumProxy();
seleniumProxy.setHttpProxy("localhost:9101");
DesiredCapabilities capabilities = new DesiredCapabilities();
capabilities.setCapability(CapabilityType.PROXY, seleniumProxy);
capabilities.setCapability("ie.setProxyByServer", true);
File file = new File("C:\\path\\IEDriverServer.exe");
System.setProperty("webdriver.ie.driver", file.getAbsolutePath());
driver = new InternetExplorerDriver(capabilities);
driver.get("www.google.com");
I get the below error when trying to access google.com from webdrviver
From Process method
Nov 09, 2014 2:07:58 AM net.lightbody.bmp.proxy.util.Log info
INFO: java.net.UnknownHostException: www.google.com when requesting http://www.google.com/
Browsermob uses xbill DNS instead of regular Java/native DNS resolution, which may not play nice with your VPN. The latest browsermob snapshot allows you to enable native DNS fallback by setting the system property bmp.allowNativeDnsFallback to true:
System.setProperty("bmp.allowNativeDnsFallback", "true");
proxyServer = new ProxyServer(9101);
proxyServer.start();
You can get the latest snapshot at the browsermob github page.
I am trying to prevent Javascript from changing the site's source code I'm testing with Selenium. The problem is, I can't just simply turn Javascript off in the Webdriver, because I need it for a test. Here's what I'm doing for the Firefox Webdriver:
firefoxProfile.setPreference("permissions.default.image", 2);
firefoxProfile.setPreference("permissions.default.script", 2);
firefoxProfile.setPreference("permissions.default.stylesheet", 2);
firefoxProfile.setPreference("permissions.default.subdocument", 2);
I don't allow Firefox to load any Images, Scripts and Stylesheets.
How can I do this with the Internet Explorer Webdriver and the Chrome Webdriver? I have not found any similar preferences. Or is there even a more elegant way to stop the webdrivers from loading the site's JS Files after all?
Thank you!
Solution is to use proxy. Webdriver integrates very well with browsermob proxy: http://bmp.lightbody.net/
private WebDriver initializeDriver() throws Exception {
// Start the server and get the selenium proxy object
ProxyServer server = new ProxyServer(proxy_port); // package net.lightbody.bmp.proxy
server.start();
server.setCaptureHeaders(true);
// Blacklist google analytics
server.blacklistRequests("https?://.*\\.google-analytics\\.com/.*", 410);
// Or whitelist what you need
server.whitelistRequests("https?://*.*.yoursite.com/.*. https://*.*.someOtherYourSite.*".split(","), 200);
Proxy proxy = server.seleniumProxy(); // Proxy is package org.openqa.selenium.Proxy
// configure it as a desired capability
DesiredCapabilities capabilities = new DesiredCapabilities();
capabilities.setCapability(CapabilityType.PROXY, proxy);
// start the driver ;
Webdriver driver = new FirefoxDriver(capabilities);
//WebDriver driver = new InternetExplorerDriver();
return driver;
}
Probably the easiest way to accomplish what you want in a cross-browser way is to use a proxy. This would allow you to intercept requests for resources, and block them. This would also have the advantage of using the same code for all browsers, rather than having to special-case each browser with settings unique to that browser.