browserMob proxy with phantomjs throws "java.net.UnknownHostException" for http protocol - java

Trying to use PhantomJS(com.codeborne:phantomjsdriver:1.2.1) for some headless browser testing along with BrowserMob Proxy(browsermob-proxy-2.0-beta-9) to capture HAR files and Javascript execution.
It works for urls with https(eg. https://www.google.com) and I get the HAR.
However for http(eg. http://www.google.com) I get the following error in the BrowserMob logs
INFO 02/02 22:45:03 n.l.b.p.j.h.HttpSer~ - Version Jetty/5.1.x
INFO 02/02 22:45:03 n.l.b.p.j.u.Contain~ - Started HttpContext[/,/]
...
INFO 02/02 22:46:29 n.l.b.p.h.BrowserMo~ - java.net.UnknownHostException: www.google.com when requesting http://www.google.com/
INFO 02/02 22:46:54 n.l.b.p.j.u.Threade~ - Stopping Acceptor ServerSocket[addr=/0.0.0.0,localport=13000]
...
Following is how I setup PhantomJS
public RemoteWebDriver getDriverInstance() {
DesiredCapabilities capabilities = new DesiredCapabilities();
capabilities.setJavascriptEnabled(true);
//code to get Proxy is below
capabilities.setCapability(CapabilityType.PROXY, getProxyObject());
capabilities.setCapability(PhantomJSDriverService.PHANTOMJS_EXECUTABLE_PATH_PROPERTY, "./bin/phantomjs");
capabilities.setCapability(CapabilityType.ACCEPT_SSL_CERTS, true);
capabilities.setCapability(PhantomJSDriverService.PHANTOMJS_CLI_ARGS, new String[] {"--web-security=no", "--ssl-protocol=any", "--ignore-ssl-errors=yes"});
WebDriver webDriver = new PhantomJSDriver(capabilities);
return (RemoteWebDriver) webDriver;
}
public Proxy getProxyObject() {
Proxy proxy = new Proxy();
//publicIp is localhost for testing purposes.
String proxyLocation = this.getPublicIp() + ":" + this.getBrowserMobProxyPort();
proxy.setHttpProxy(proxyLocation);
proxy.setFtpProxy(proxyLocation);
proxy.setSslProxy(proxyLocation);
return proxy;
}
Still looking for a solution.
Is it normal to expect such messages from BrowserMob?
I, most probably have not setup something correctly or missed a part. Would be awesome if anyone who has faced this issue, help me out or point me to a solution. I have done some searching but not found a solution that resolves this.
Also if there is additional information needed, please let me know.

I am using a newer version of BrowserMob Proxy, but the following Scala code works for me in loading HTTP and HTTPS websites:
import java.io.File
import net.anthavio.phanbedder.Phanbedder
import net.lightbody.bmp.BrowserMobProxyServer
import net.lightbody.bmp.client.ClientUtil
import net.lightbody.bmp.core.har.HarEntry
import org.apache.commons.io.FileUtils
import org.openqa.selenium.OutputType
import org.openqa.selenium.phantomjs.PhantomJSDriver
import org.openqa.selenium.phantomjs.PhantomJSDriverService._
import org.openqa.selenium.remote.{CapabilityType, DesiredCapabilities}
import scala.collection.JavaConversions._
object PhantomJSTest {
def main(args: Array[String]) {
val bm = new BrowserMobProxyServer
bm.start(0)
val proxy = ClientUtil.createSeleniumProxy(bm)
val phantomjs = Phanbedder.unpack()
val capabilities = new DesiredCapabilities
capabilities.setCapability(CapabilityType.PROXY, proxy)
capabilities.setCapability(PHANTOMJS_EXECUTABLE_PATH_PROPERTY,
phantomjs.getAbsolutePath())
capabilities.setCapability(PHANTOMJS_CLI_ARGS,
Array[String]("--web-security=no",
"--ssl-protocol=any",
"--ignore-ssl-errors=yes"))
val driver = new PhantomJSDriver(capabilities)
run(bm, driver, "http://www.google.com")
run(bm, driver, "https://www.google.com")
driver.quit
bm.stop
}
def run(bm: BrowserMobProxyServer, driver: PhantomJSDriver, url: String) {
bm.newHar(url)
driver.get(url)
val har = bm.getHar
har.getLog.getEntries.foreach { e: HarEntry =>
println(e.getRequest.getUrl)
}
val file = new File(s"screenshot-${System.currentTimeMillis}.png")
FileUtils.copyFile(driver.getScreenshotAs(OutputType.FILE), file)
println(s"Captured loading of ${url} screenshot to ${file.getCanonicalPath}")
}
}
Here are the libraries I am using (from my build.gradle file):
compile 'commons-io:commons-io:2.4'
compile 'org.slf4j:slf4j-simple:1.7.16'
compile 'net.lightbody.bmp:browsermob-core-littleproxy:2.1.0-beta-4'
compile 'org.seleniumhq.selenium:selenium-java:2.45.0'
compile 'com.codeborne:phantomjsdriver:1.2.1'
compile 'net.anthavio:phanbedder-2.1.1:1.0.0'
Hope this helps you debug the issue you are running in to.

Related

How to get context and switch to webview context

I'm testing a Windows hybrid application, I'm using the codes below to get contexts but I got an UnsupportedCommandException when I launch it.
Here's my code :
public void initialize() throws MalformedURLException {
DesiredCapabilities capabilities = new DesiredCapabilities();
capabilities.setCapability(MobileCapabilityType.PLATFORM_NAME, "Windows");
capabilities.setCapability(MobileCapabilityType.PLATFORM_VERSION, "10");
capabilities.setCapability(MobileCapabilityType.DEVICE_NAME, "Max");
capabilities.setCapability("app", "D:\\Users\\Max\\Desktop\\TI\\ti.exe");
driver = new AppiumDriver<>(new URL("http://localhost:4723/wd/hub"), capabilities);
Set<String> contextNames = driver.getContextHandles();
for (String contextName : contextNames) {
System.out.println(contextName);
}
driver.context((String) contextNames.toArray()[1]);
}
Here's the output on the Appium Server:
Appium server screen
It says that the command contexts is not recognized.
I'm using :
Appium Desktop v1.20.2
Appium Java client v7.5.1
WinAppDriver v1.2.1
The first of all, you need to get all contexts. More info in official docs
Here how I implemented it in tests.
In some Page Object files I keep Android contexts.
ANDROID_CONTEXTS = {
'webview': 'WEBVIEW_ru.myapp',
'native': 'NATIVE_APP'
}
In some tests I switch context from Native to Webview.
#allure.link(url='https://jira.project.tech/browse/TEST-1', name='TEST-1 - Fill payment form')
#allure.title('Fill payment form')
def test_card_standard_1_month(appdriver):
Paywall(appdriver).press_one_month_button()
PaymentsPage(appdriver).select_card_payment()
PaymentsPage(appdriver).press_payment_button()
appdriver.switch_to.context(ANDROID_CONTEXTS['webview'])
Payform(appdriver).fill_and_submit_payform()
appdriver.switch_to.context(ANDROID_CONTEXTS['native'])
assert SuccessPayment(appdriver).get_successful_payment_title_text() == 'Your subscription is successful!'
You can check all available contexts in your app. More info here -> http://appium.io/docs/en/commands/context/set-context/

Setting up the ChromeDriver for selenide using experimental features (download.default_directory) in conjunction with using selenide browser defaults

I'm looking for the best way to set up the chromium browser to allow downloads while accepting the default selenide settings.
We had the ChromeDriver working based solely on the selenium system properties (headless, windowSize, etc.)
I now have file downloads working, but it's via hard coding properties into the chrome driver that are also defined in the system configuration file.
So I'm wondering how do I allow the download of files into a specified folder (dynamically when creating the ChromeDriver) while still using the other default settings in the selenide Configuration.
So, my questions are:
What is the best way to merge System defined properties for selenide with the experimental file download properties needed to download files in Chrome? Is there a way to add experimental properties to the ChromeDriver while letting it read in the default properties?
Relatedly, is there a way of using the WebDriverProvider to read in Selenium options, which are being set correctly in the configuration, but are not present in the DesiredCapabilites being passed in.
Finally (additional context for my end goal) we're trying to save files based on the names of the testng suite they are being run from. I know how to get the suite name when creating the chromedriver, but I'm not sure the best way to make it available to the webdriverprovider, if that is the final solution.
Sample 1: Working download function:
private void saveDownloadsIntoDesiredDirectory(String downloadFolderName) {
if (Configuration.browser.equals("chrome")) {
HashMap<String, Object> chromePrefs = new HashMap<String, Object>();
chromePrefs.put("profile.default_content_settings.popups", 0);
//THIS must be the canonicalPath,otherwise it won't work on Windows.
try {
chromePrefs.put("download.default_directory", new File(downloadFolderName).getCanonicalPath());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
chromePrefs.put("download.prompt_for_download", false);
chromePrefs.put("download.directory_upgrade", true);
chromePrefs.put("safebrowsing.enabled", true);
//THIS took forever to find.
chromePrefs.put("safebrowsing.disable_download_protection",true);
ChromeOptions options = new ChromeOptions();
options.setExperimentalOption("prefs", chromePrefs);
options.addArguments("--disable-extensions");
options.addArguments("--headless");
options.addArguments("--no-sandbox");
options.addArguments("--window-size=1280,1024");
WebDriver driver = new ChromeDriver(options);
driver.getTitle();
WebDriverRunner.setWebDriver(driver);
}
}
I thought the proper way to fix it might be a WebDriverProvider .. but I'm not seeing the benefits of it. This is where it currently stands. The duplication of configuration parameters below can't be the best way to do this.
package core;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Set;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;
import org.openqa.selenium.remote.DesiredCapabilities;
import com.codeborne.selenide.Configuration;
import com.codeborne.selenide.WebDriverProvider;
public class SaveFileWebDriverProviderShared implements WebDriverProvider {
#Override
public WebDriver createDriver(DesiredCapabilities capabilities) {
System.out.println("CLE headless" + Configuration.headless);
System.out.println(Configuration.browserSize);
DesiredCapabilities dc2 = Configuration.browserCapabilities;
Set<String> test= dc2.getCapabilityNames();
HashMap<String, Object> chromePrefs = new HashMap<String, Object>();
chromePrefs.put("profile.default_content_settings.popups", 0);
//THIS must be the canonicalPath,otherwise it won't work on Windows.
// try {
// chromePrefs.put("download.default_directory", new File("/tmp/downloadTest",afs.getActiveSuite()) );
File downloadFolder = new File("/tmp/downloadTest/CLETEst");
downloadFolder.mkdir();
//THIS must be the canonicalPath,otherwise it won't work on Windows.
try {
chromePrefs.put("download.default_directory", downloadFolder.getCanonicalPath() );
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
chromePrefs.put("download.prompt_for_download", false);
chromePrefs.put("download.directory_upgrade", true);
chromePrefs.put("safebrowsing.enabled", true);
//THIS took forever to find.
chromePrefs.put("safebrowsing.disable_download_protection",true);
ChromeOptions options = new ChromeOptions();
options.setExperimentalOption("prefs", chromePrefs);
options.addArguments("--disable-extensions");
options.addArguments("--no-sandbox");
if(Configuration.headless) {
options.addArguments("--headless");
}
if(Configuration.browserSize != null) {
options.addArguments("--window-size="+Configuration.browserSize.replace('x', ','));
}
options.merge(capabilities);
ChromeDriver driver = new ChromeDriver(options);
return driver;
}
}
Technical detail:
Starting ChromeDriver 78.0.3904.11 (eaaae9de6b8999773fa33f92ce1e1bbe294437cf-refs/branch-heads/3904#{#86})

How to disable JavaScript in browser using Selenium (Java)?

In my feature automation, I need to disable JavaScript in browser and run the flow. How to disable JavaScript?
Tried DesiredCapabilities for firefox and Chrome.
DesiredCapabilities dc = new DesiredCapabilities();
dc.setCapability(CapabilityType.SUPPORTS_JAVASCRIPT, false)
And
DesiredCapabilities dc = new DesiredCapabilities();
dc.setJavascriptEnabled(false);
For firefox, tried
1) Setting up profile for firefox
2) Adding add-on - noScript.xpi
3) profile.setPreference("javascript.enabled", false);
4) Through UI, tried changing the flag - "javascript.enabled" in "about:config" to false. Here, opened firefox and gave "about:config" getting a warning - "This might void your warranty!". There is a button - "I'll be careful, I promise!" with id - warningButton. This button should be clicked to proceed further. To click this button, used driver.findElement(By.id("warningButton")).click(); but it not work.
All the above options are not working. Any advice will be helpful.
I don't know Java, but maybe a solution for Python 3 will help you.
in Python, you can use Options() instead of FirefoxProfile() to deactivate JavaScript:
from selenium.webdriver.firefox.options import Options
options = Options()
options.preferences.update({"javascript.enabled": False})
driver = webdriver.Firefox(options=options)
driver.get('about:config')
Maybe Java this:
FirefoxOptions options = new FirefoxOptions();
options.preferences.update({"javascript.enabled": False});
WebDriver driver = new FirefoxDriver(options);
driver.get('about:config')
You change the preference value using profile with lots of options:
DesiredCapabilities capabilities = new DesiredCapabilities();
// setCapability(SUPPORTS_JAVASCRIPT, javascriptEnabled);
capabilities.setJavascriptEnabled(false);
FirefoxBinary binary = new FirefoxBinary( new File( binaryPath ) );
FirefoxProfile profile = new FirefoxProfile();
//profile.setPreference("preferenceName", "Value");
profile.setPreference("javascript.enabled", false);
RemoteWebDriver driver = new FirefoxDriver(binary, profile, capabilities);
To view the preferences, you can visit the URL about:config
#See
Chrome driver to disable JavaScript issue
chromium-command-line-switches
Truse me this was random trial but works perfectly for me
from selenium import webdriver
options= webdriver.ChromeOptions()
chrome_prefs = {}
options.experimental_options["prefs"] = chrome_prefs
chrome_prefs["profile.default_content_settings"] = {"javascript": 2}
chrome_prefs["profile.managed_default_content_settings"] = {"javascript": 2}
driver = webdriver.Chrome("your chromedriver path here",options=options)
driver.get('https://google.com/search?q=welcome to python world')
Example image here:-https://i.stack.imgur.com/DdKZQ.png
As per Selenium 3.6 Java Client Release, the easiest way to disable Javascript in the browser would be to set the setJavascriptEnabled argument through an instance of DesiredCapabilities to False and merge it through an instance of FirefoxOptions as follows:
package demo;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.firefox.FirefoxOptions;
import org.openqa.selenium.remote.DesiredCapabilities;
public class Q46883024_setJavascriptEnabled
{
public static void main(String[] args)
{
System.setProperty("webdriver.gecko.driver", "C:\\Utility\\BrowserDrivers\\geckodriver.exe");
DesiredCapabilities dc = new DesiredCapabilities();
dc.setJavascriptEnabled(false);
FirefoxOptions op = new FirefoxOptions();
op.merge(dc);
WebDriver driver = new FirefoxDriver(op);
driver.get("https://google.com");
driver.quit();
}
}
While execution, the browser you are using may override the setJavascriptEnabled settings.
this works:
FirefoxOptions options = new FirefoxOptions();
options.addPreference("javascript.enabled", false);
This is how you can do it for Chrome in Java.
// import org.openqa.selenium.chrome.ChromeOptions;
ChromeOptions options = new ChromeOptions();
options.addArguments("user-agent=\"Mozilla/5.0 (compatible; Googlebot/2.1; +http://www.google.com/bot.html)\"");
HashMap<String, Object> chromePrefs = new HashMap<String, Object>();
chromePrefs.put("profile.default_content_setting_values.javascript", 2);
options.setExperimentalOption("prefs", chromePrefs);
new ChromeDriver(options);
And it worked for me with ChromeDriver 2.41.578706. As a bonus I am also setting Googlebot as user-agent.
In case you need to do something with DesiredCapabilities you can also convert the options above to capabilities:
// import static org.openqa.selenium.chrome.ChromeOptions.CAPABILITY;
DesiredCapabilities capabilities = DesiredCapabilities.chrome();
capabilities.setCapability(CAPABILITY, options);
new ChromeDriver(capabilities);

How to set Proxy Authentication in seleniumWebdriver for Chrome Browser

I'm trying to Automate a web application selenium 2.0 [webdriver+java].The web application is currently deployed in our UAT servers on our local network.My test cases are executing, but I have to manually enter the Proxy Authentication details for my Chrome instance at the start of the test execution. I have tried all the solutions provided on stack overflow but still, the authentication message pops out.
This is the code I'm using in my driver initializing process
package com.misyn.ess.ui;
import java.util.Arrays;
import org.openqa.selenium.Proxy;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;
import org.openqa.selenium.remote.DesiredCapabilities;
/**
*
* #author User
*/
public class DriverClass {
private String baseUrl;
private String driverPath;
private String driverName;
private static WebDriver driver;
private static DriverClass driverClass;
private DriverClass() {
try {
baseUrl = "http://192.168.0.10:8282/ess";
driverPath = "E:\\Work_Folder\\SelTools\\chromedriver.exe";
driverName = "webdriver.chrome.driver";
//Set the location of the ChromeDriver
System.setProperty(driverName, driverPath);
//Create a new desired capability
DesiredCapabilities capabilities = DesiredCapabilities.chrome();
// Create a new proxy object and set the proxy
Proxy proxy = new Proxy();
proxy.setHttpProxy("192.168.0.200:3128");
proxy.setSocksUsername("avishka");
proxy.setSocksPassword("12345678");
//Add the proxy to our capabilities
capabilities.setCapability("proxy", proxy);
//Start a new ChromeDriver using the capabilities object we created and added the proxy to
driver = new ChromeDriver(capabilities);
//Navigation to a url and a look at the traffic logged in fiddler
driver.navigate().to(baseUrl);
// System.setProperty(driverName, driverPath);
// driver = new ChromeDriver();
// driver.get(baseUrl);
} catch (Exception e) {
e.printStackTrace();
}
}
}
Can anyone give me a solution how to give this proxy username and password thing from the application itself than manually entering details on the pop-up(Authentication), any help would be much appreciated.Thanks
the currently answered one is only for
As of Selenium 3.4 it is still in beta
Right now implementation is only done for InternetExplorerDriver
Where I'm using selenium 3.0 and Google Chrome as my web browser.
You can do via MultiPass for HTTP basic authentication
Download the extension from
https://chrome.google.com/webstore/detail/multipass-for-http-basic/enhldmjbphoeibbpdhmjkchohnidgnah
Download the extension as crx. You can get it as crx from chrome-extension-downloader
After that the config is simple.
import java.io.File;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;
/**
*
* #author Phystem
*/
public class ChromeAuthTest {
WebDriver driver;
public ChromeAuthTest() {
System.setProperty("webdriver.chrome.driver", "chromedriver.exe");
}
private void initDriver() {
ChromeOptions cOptions = new ChromeOptions();
cOptions.addExtensions(new File("MultiPass-for-HTTP-basic-authentication_v.crx"));
driver = new ChromeDriver(cOptions);
configureAuth(
"https://the-internet.herokuapp.com/basic_auth",
"admin",
"admin");
}
private void configureAuth(String url, String username, String password) {
driver.get("chrome-extension://enhldmjbphoeibbpdhmjkchohnidgnah/options.html");
driver.findElement(By.id("url")).sendKeys(url);
driver.findElement(By.id("username")).sendKeys(username);
driver.findElement(By.id("password")).sendKeys(password);
driver.findElement(By.className("credential-form-submit")).click();
}
public void doTest() {
initDriver();
driver.get("https://the-internet.herokuapp.com/basic_auth");
System.out.println(driver.getTitle());
driver.quit();
}
public static void main(String[] args) {
new ChromeAuthTest().doTest();
}
}
I have used a sample site for testing.
Provide your url,username and password in the configure Auth function and try
public class DriverClass {
private String baseUrl;
private String driverPath;
private String driverName;
private static WebDriver driver;
private static DriverClass driverClass;
public DriverClass() {
try {
baseUrl = "http://192.168.0.10:8282/ess";
driverPath = "E:\\Work_Folder\\SelTools\\chromedriver.exe";
driverName = "webdriver.chrome.driver";
System.setProperty(driverName, driverPath);
Proxy proxy = new org.openqa.selenium.Proxy();
proxy.setSslProxy("192.168.0.200" + ":" + 3128);
proxy.setFtpProxy("192.168.0.200" + ":" + 3128);
proxy.setSocksUsername("avishka");
proxy.setSocksPassword("12345678");
DesiredCapabilities desiredCapabilities = DesiredCapabilities.chrome();
desiredCapabilities.setCapability(CapabilityType.PROXY, proxy);
driver = new ChromeDriver(desiredCapabilities);
driver.get(baseUrl);
} catch (Exception e) {
e.printStackTrace();
}
}
}
The proxy setting has been added with desired capabilities to pass values to proxy authentication,worked finally
This code (from Avishka Perera's answer) does not work for me:
proxy.setSocksUsername("avishka");
proxy.setSocksPassword("12345678");
The username and password set in this way do not take effect for the http/https proxy - the Proxy Authentication box still popped up.
I'm using Selenium java 3.141.0, ChromeDriver 2.33 and chrome 70. What works for me is to follow Mike's answer here Selenium using Python: enter/provide http proxy password for firefox .
Create the zip file, then add the extension like this:
ChromeOptions chromeOptions = new ChromeOptions();
chromeOptions.addExtensions(new File("src/test/resources/proxy.zip"));
WebDriver driver = new ChromeDriver(chromeOptions);
One catch is that the above code will run into error if you set "--headless" argument because chrome in headless mode cannot have extension (Is it possible to run Google Chrome in headless mode with extensions?). If your Chrome runs in Docker container and cannot show the UI, then to get this solution work, you'll need to run with Xvfb instead of in headless mode.
Simple method to add authenticated proxy using selenium wire in Both firefox and chrome
In python
Step:1
pip3 install selenium-wire
Step:2
from seleniumwire import webdriver
from selenium import webdriver
step:3
Add proxy in below-mensioned format
proxy= "username:password#ip:port"
options = {'proxy': {'http': proxy, 'https': proxy, 'no_proxy': 'localhost,127.0.0.1,dev_server:8080'}}
step:4
pass proxy as an argument
CHROME
driver = webdriver.Chrome(options=chrome_options, executable_path="path of chrome driver", seleniumwire_options=options)
Firefox
driver = webdriver.Firefox(seleniumwire_options=options, executable_path="path of firefox driver", options=firefox_options)
step:5
Verify proxy applied by requesting the url https://whatismyipaddress.com/
time.sleep(20)
driver.get("https://whatismyipaddress.com/")
Note:
But selenium log shows it runs in without proxy because we are using an external package to apply proxy.
I know this is an old thread, still leaving a solution which worked for me using browsermob proxy, for someone who still needs an option.
Maven dependency:
<dependency>
<groupId>org.seleniumhq.selenium</groupId>
<artifactId>selenium-java</artifactId>
<version>4.0.0</version>
</dependency>
<dependency>
<groupId>net.lightbody.bmp</groupId>
<artifactId>browsermob-core</artifactId>
<version>2.1.5</version>
</dependency>
Java Code:
// I am using firefox
System.setProperty("webdriver.gecko.driver", "C:\\Selenium\\geckodriver.exe");
BrowserMobProxy browsermobProxy = new BrowserMobProxyServer();
browsermobProxy.setChainedProxy(new InetSocketAddress(PROXY_HOSTNAME, PROXY_PORT));
browsermobProxy.chainedProxyAuthorization(PROXY_USERNAME, PROXY_PASSWORD, AuthType.BASIC);
browsermobProxy.start(0);
FirefoxBinary firefoxBinary = new FirefoxBinary();
FirefoxOptions firefoxOptions = new FirefoxOptions();
firefoxOptions.setBinary(firefoxBinary );
firefoxOptions.setProfile(firefoxProfile);
firefoxOptions.setProxy(ClientUtil.createSeleniumProxy(browsermobProxy));
WebDriver webDriverWithProxy = new FirefoxDriver(firefoxOptionsWithProxy);
webDriverWithProxy.get("https://stackoverflow.com/");
The approach that worked perfectly fine for me is by using AutoIT.
Install autoIT and prepare a simple script as shown in the picture attached and execute the script file from your testscript using Runtime.getRuntime().exec("\YOUR_SCRIPT.exe") before navigating to the baseURL.

How to Setup Private Proxy with Selenium?

I've been trying for days to setup a private proxy (with authentication) in Selenium using Firefox. However, no matter what I do I'v been unsuccessful.
Currently, I have tried the following two approaches and in both cases Firefox launches normally without any proxy.
Proxy proxy = new Proxy();
proxy.setHttpProxy(proxyHost + proxyPort);
proxy.setSocksUsername(proxyUsername);
proxy.setSocksPassword(proxyPass);
DesiredCapabilities cap = DesiredCapabilities.firefox();
cap.setCapability(CapabilityType.PROXY, proxy);
WebDriver driver = new FirefoxDriver(cap);
driver.get("http://google.com");
I have also tried the following:
FirefoxProfile profile = new FirefoxProfile();
profile.setPreference("network.proxy.type", 1);
profile.setPreference("network.proxy.http", proxyHost);
profile.setPreference("network.proxy.http_port", proxyPort);
profile.setPreference("network.proxy.http", "user:pass#1.1.1.1");
profile.setPreference("network.proxy.http_port", proxyPort);
WebDriver driver = new FirefoxDriver(profile);
driver.get("http://google.com");
How can I setup http private proxies (with user name and password in Selenium with Firefox)?
I am using Java.
Thanks
const {Builder, By, Key, until} = require('selenium-webdriver');
const proxy = require('selenium-webdriver/proxy');
(async function example(){
let driver = await new Builder().forBrowser('firefox').setProxy(proxy.manual({
http: 'zproxy.lum-superproxy.io:22225',
https: 'zproxy.lum-superproxy.io:22225'
})).build()
try {
await driver.get('http://lumtest.com/myip.json');
driver.switchTo().alert()
.sendKeys('lum-customer-USERNAME-zone-YOURZONE'+Key.TAB+'PASSWORD');
driver.switchTo().alert().accept();
} finally {
await driver.quit();
}
})();
Here is my sample code when I use Luminati proxy for Selenium.
You can try using browsermob proxy.
Here you go for example
Find solution:
proxy = Proxy({
'proxyType': ProxyType.MANUAL,
'httpProxy': PROXY_HOST,
'socksUsername': 'name',
'socksPassword': 'pass'
})
driver = webdriver.Firefox(proxy=proxy)

Categories

Resources