I am a newbie to Automation.Trying to execute below code. Its giving me jsonexception.
I have read on previous answers that desired capabilities is deprecated. I have also tried using chromeoption.merge(capabilities) but even that is not working. Code below. Please help
Exception :
WARNING: Attempt to convert JsonElement from GSON. This functionality is deprecated. Diagnostic stacktrace follows
org.openqa.selenium.json.JsonException: Stack trace to determine cause of warning
public class base {
public WebDriver driver;
public Properties prop;
public WebDriver initializeDriver() throws IOException {
prop = new Properties();
FileInputStream fis = new FileInputStream(
"E:\\SeleniumWorkspace\\E2EProject\\src\\main\\java\\resources\\data.properties");
prop.load(fis);
String browserName = prop.getProperty("browser");
if (browserName.equals("chrome")) {
System.setProperty("webdriver.chrome.driver", "F:\\Setups\\chromedriver_win32Chrome90\\chromedriver.exe");
ChromeOptions options = new ChromeOptions();
options.addArguments("--ignore-ssl-errors=yes");
options.addArguments("--ignore-certificate-errors");
options.addArguments("--start-maximized");
driver = new ChromeDriver(options);
}
if (browserName.equals("firefox")) {
driver = new FirefoxDriver();
}
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
return driver;
}
I do not see any issue with your code. However, If I may suggest, you may use the below instead of setting the property each time
To automatically set the property for chrome:
WebDriverManager.chromedriver().setup();
Go here to see for other drivers: WebDriverManager
Now that being said, I think you might be using an old version of Selenium, add the below in your pom.xml
<dependency>
<groupId>org.seleniumhq.selenium</groupId>
<artifactId>selenium-java</artifactId>
<version>3.141.59</version>
<scope>compile</scope>
</dependency>
I am using the above dependencies for running in "headless" mode and my tests do not throw any error for ChromeOptions.
Related
I'm using Web driver manager to setup chrome driver. When setting up the driver I want to add some chrome options? How can I do it when using web driver manager?
I checked the WebDriverManager API but couldn't find any clue..
As of WebDriverManager 5.x you can instantiate the webDriver directly via the WebDriverManager builder with additional capabilities this way (in java) :
WebDriver driver;
//...
ChromeOptions chromeOptions = new ChromeOptions();
chromeOptions.addArguments("--headless");
//...
//chromeOptions.addArguments(<another-option>);
//...
driver = WebDriverManager.chromedriver().capabilities(chromeOptions).create();
The capabilities method take a Capabilities as param.
Lucky we are, ChromeOptions implements the Capabilities interface.
public void WebDriverManagerTest()
{
//setup the chromedriver using WebDriverManager
WebDriverManager.chromedriver().setup();
//Create Chrome Options
ChromeOptions option = new ChromeOptions();
option.addArguments("--test-type");
option.addArguments("--disable-popup-bloacking");
DesiredCapabilities chrome = DesiredCapabilities.chrome();
chrome.setJavascriptEnabled(true);
option.setCapability(ChromeOptions.CAPABILITY, option);
//Create driver object for Chrome
WebDriver driver = new ChromeDriver(option);
//Navigate to a URL
driver.get("http://toolsqa.com");
//quit the browser
driver.quit();
}
Found the answer.. Check above!
This is the example code:
public class Test1{
#Test
public void WebDriverManagerTest()
{
//setup the chromedriver using WebDriverManager
WebDriverManager.chromedriver().setup();
//Create driver object for Chrome
WebDriver driver = new ChromeDriver();
//Navigate to a URL
driver.get("http://toolsqa.com");
//quit the browser
driver.quit();
}
}
from https://pypi.org/project/webdriver-manager/, pass it in after .install()
from selenium import webdriver
from webdriver_manager.opera import OperaDriverManager
options = webdriver.ChromeOptions()
options.add_argument('allow-elevated-browser')
options.binary_location = "C:\\Users\\USERNAME\\FOLDERLOCATION\\Opera\\VERSION\\opera.exe"
driver = webdriver.Opera(executable_path=OperaDriverManager().install(), options=options)
I want to use Custom driver provider with my configuration.
But in this case selenium instead selenide is used.
Going such way i need to specify path to chromedriver.exe, but Selenide does not require to download it.
How can i use custom driver provider without setting
System.setProperty("webdriver.chrome.driver", "path/chromedriver.exe");
Call webdriver:
switch (conf_browser) {
case "chrome":
Configuration.browser = DriverProviderChrome.class.getName();
break;
WebdriverProvider:
public class DriverProviderChrome implements WebDriverProvider {
#Override
public ChromeDriver createDriver(DesiredCapabilities capabilities) {
File adf = new File("drivers");
System.setProperty("webdriver.chrome.driver", "drivers/chromedriver/win32/75.0.3770.90/chromedriver.exe");
capabilities = DesiredCapabilities.chrome();
LoggingPreferences logs = new LoggingPreferences();
logs.enable(LogType.DRIVER, Level.ALL);
ChromeOptions chromeOptions = new ChromeOptions();
chromeOptions.addArguments("--incognito");
chromeOptions.addArguments("start-maximized");
chromeOptions.addArguments("disable-infobars");
chromeOptions.addArguments("--user-data-dir=C:\\Users\\AntonK\\AppData\\Local\\Google\\Chrome\\User Data\\Profile 1");
chromeOptions.setCapability(CapabilityType.LOGGING_PREFS, logs);
capabilities.setCapability(ChromeOptions.CAPABILITY, chromeOptions);
TestBase_working.log(capabilities.getVersion());
chromeOptions.merge(capabilities);
return new ChromeDriver(chromeOptions);
}
}
Selenide calls WebDriverFactory to download chromedriver to the local maven repo and init webdriver.chrome.driver System property.
You can set driver path automatically this way:
WebDriverManager.chromedriver().setup();
Chromedriver path is stored here, but mind that path is not static, it changes when driver gets updated automatically:
WebDriverManager.chromedriver().binaryPath
I'm creating tests(ui tests) on windows 10 machine. They works well, but few days ago my boss told me that we need to run our tests on linux. I'm downloaded linux driver and change it in System.setProperty("webdriver.chrome.driver", "chromedriver"); but after trying to run this test i got java.lang.ExceptionInInitializerError(it was latest driver with latest browser). After it i changed my code that allow me to run test, but connection to driver is remote. I don't like this way. May be some one of you know which driver will work on linux without code change in driver initialization part?
E.g.
windows driver initialization :
private static WebDriver driver = new ChromeDriver();
private static WebDriverWait wait = new WebDriverWait(driver, 30);
#Given("^blah blah$")
public void some_method() {
System.setProperty("webdriver.chrome.driver", "chromedriver.exe");
}
linux driver initialization :
public abstract class InitDrivers{
private static DesiredCapabilities capability = DesiredCapabilities.chrome();
public static WebDriver driver;
static {
try {
driver = new RemoteWebDriver(new URL("http://127.0.0.1:9515"),capability);
} catch (MalformedURLException e) {
e.printStackTrace();
}
}
public static WebDriverWait wait = new WebDriverWait(driver, 30);
public class CallDoctorTestStep extends InitDrivers{
#Given("^blah blah$")
public void some_method() throws MalformedURLException{
//System.setProperty("webdriver.chrome.driver","chromedriver.exe");
}
See solution in Selenium NoSuchSession on linux
java.lang.ExceptionInInitializerError
java.lang.ExceptionInInitializerError implies that an unexpected exception has occurred in a Static Initializer. This error is thrown to indicate that an exception occurred during evaluation of a static initializer or the initializer for a static variable.
An ExceptionInInitializerError is raised if something goes wrong in the static initializer block. An example below :
class Anton
{
static
{
// if something goes wrong ExceptionInInitializerError will be thrown
}
}
Static variables are initialized in static blocks and can throw these errors.
Problem :
In your Linux Driver Initialization code block, initially you have mentioned :
private static DesiredCapabilities capability = DesiredCapabilities.chrome();
Then invoked the RemoteWebDriver as follows :
driver = new RemoteWebDriver(new URL("http://127.0.0.1:9515"),capability);
But in the following steps you have again tried to :
System.setProperty("webdriver.chrome.driver", "chromedriver.exe");
This sequence of events creates the error.
Solution :
As you have already declared the WebDriver instance as :
public static WebDriver driver;
Next, use System.setProperty() :
System.setProperty("webdriver.chrome.driver", "/path/to/chromedriver"); // <- remove the .exe part here following Linux style
Now you need to initialize the RemoteWebDriver instance as follows :
driver = new RemoteWebDriver(new URL("http://127.0.0.1:9515"),capability);
As the WebDriver instance (which is static) and Web Browser instance is active now you must not change the attributes during the Test Execution.
Note : You can find a detailed discussion in exception in initializer error
I am trying to launch IE but nothing happens with Selenium Java code below:
protected WebDriver ieBrowserSetUp() throws Exception {
// Read the properties file
Properties prop = getProperties();
System.setProperty("webdriver.ie.driver", prop.getProperty("IEDriverPath"));
driver = new InternetExplorerDriver();
driver.navigate().to("https://www.google.com");
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
driver.manage().window().maximize();
DesiredCapabilities caps = DesiredCapabilities.internetExplorer();
caps.setCapability(InternetExplorerDriver.INITIAL_BROWSER_URL, "");
WebDriver driver= new InternetExplorerDriver(caps);
System.out.println("Internet Explorer Browser Setup Done Successfully");
return driver;
}
It is working fine with the Firefox and Chrome Webdriver. I saw in one of the posts the Protected Mode Settings needs to be changed. Is there a workaround as the settings is disabled at work considering I am not a Windows admin. The path is pointed to IEDriverServer.exe I downloaded instead of the "Windows-installed-and-defaulted" IE application.
I solved it with this:
System.setProperty("webdriver.ie.driver", prop.getProperty("IEDriverPath"));
DesiredCapabilities caps = DesiredCapabilities.internetExplorer();
caps.setCapability(InternetExplorerDriver.INTRODUCE_FLAKINESS_BY_IGNORING_SECURITY_DOMAINS, true); //disable protected mode settings
caps.setCapability("initialBrowserUrl", url);
driver = new InternetExplorerDriver(caps);
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.