Grid concept in Selenium [closed] - selenium-grid

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 years ago.
Improve this question
I have written coding for browser opening with grid concept. I wrote the following code. I need to know its correct or wrong.
properties
----------
HUB=localhost
PORT=4444
Browser = chrome
Url=http://demo.guru99.com/v4/index.php
Code
----
package processor;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Properties;
import org.openqa.selenium.Platform;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.ie.InternetExplorerDriver;
import org.openqa.selenium.remote.DesiredCapabilities;
import org.openqa.selenium.remote.RemoteWebDriver;
public class Browser {
public static void main(String[] args) throws FileNotFoundException, IOException {
RemoteWebDriver driver;
Properties prop;
prop = new Properties();
prop.load(new FileInputStream("./config.properties"));
String hub = prop.getProperty("HUB");
String port = prop.getProperty("PORT");
String browser = prop.getProperty("Browser");
String url = prop.getProperty("Url");
if (browser.equalsIgnoreCase("chrome") || browser.equalsIgnoreCase("ie")
|| browser.equalsIgnoreCase("firefox")) {
if (browser.equalsIgnoreCase("chrome")) {
try {
DesiredCapabilities dc;
dc = new DesiredCapabilities();
dc.setBrowserName(browser);
dc.setPlatform(Platform.WINDOWS);
System.setProperty("webdriver.chrome.driver", "./drivers/chromedriver.exe");
driver = new ChromeDriver();
System.out.println("Chrome Browser is Initialising..........");
driver.manage().window().maximize();
driver.get(url);
} catch (Exception e) {
System.out.println("Problem Occurred while Initialising Chrome Browser. Check for the Driver Name & Path !!!!!!!!!!");
}
}
if (browser.equalsIgnoreCase("ie")) {
try {
DesiredCapabilities dc;
dc = new DesiredCapabilities();
dc.setBrowserName(browser);
dc.setPlatform(Platform.WINDOWS);
System.setProperty("webdriver.ie.driver", "./Drivers/IEDriverServer.exe");
driver = new InternetExplorerDriver();
System.out.println("Internet Explorer is Initialising..........");
driver.manage().window().maximize();
driver.get(url);
} catch (Exception e) {
System.out.println("Problem Occurred while Initialising Internet Explorer. Check for the Driver Name & Path !!!!!!!!!!");
}
}
if (browser.equalsIgnoreCase("firefox")) {
try {
DesiredCapabilities dc;
dc = new DesiredCapabilities();
dc.setBrowserName(browser);
dc.setPlatform(Platform.WINDOWS);
driver = new FirefoxDriver();
System.out.println("Firefox is Initialising..........");
driver.manage().window().maximize();
driver.get(url);
} catch (Exception e) {
System.out.println("Problem Occurred while Initialising Firefox. Check for the Driver Name & Path !!!!!!!!!!");
}
}
}
else {
System.out.println("Invalid Browser. Check Browser Name in Properties File.......... ");
}
}
}
Kindly see the code and tell me the correct code. Grid Concept i need to apply.

To use selenium with the grid you need to start a Remote webdriver. What you're doing here is starting a local webdriver of types:
driver = new ChromeDriver();
driver = new InternetExplorerDriver();
driver = new FirefoxDriver();
This is not how you request a browser from the grid.
Furthermore, the path to the driver (System.setProperty("webdriver.chrome.driver", "./drivers/chromedriver.exe");) must be supplied to the grid, so you cannot set this in your code here.
You do this as follows:
java -jar selenium-server-standalone-2.53.0.jar -role hub -Dwebdrivers.chrome.driver=chromedriver.exe
What you are currently doing is creating local webdrivers, you are not connecting to the grid at all. Connecting to the grid is done as follows:
driver = new RemoteWebDriver(hub, dc);

Related

How to fix chromedriver error in console tab?

I have run my test script but I got this error message in the console tab:
"Starting ChromeDriver 84.0.4147.30 (48b3e868b4cc0aa7e8149519690b6f6949e110a8-refs/branch-heads/4147#{#310}) on port 30846
Only local connections are allowed.
Please see https://chromedriver.chromium.org/security-considerations for suggestions on keeping ChromeDriver safe.
ChromeDriver was started successfully.
Aug 22, 2020 5:41:42 PM org.openqa.selenium.remote.ProtocolHandshake createSession
INFO: Detected dialect: W3C"
Below is my java code:
package seleniumProjectTutorial;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
public class SeleniumWebDriver {
WebDriver driver;
public void invokeBrowser() {
try {
System.setProperty("webdriver.chrome.driver","D:\\Selenium\\Drivers\\chromedriver.exe");
driver = new ChromeDriver();
driver.manage().deleteAllCookies();
driver.manage().window().maximize();
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
driver.manage().timeouts().pageLoadTimeout(30, TimeUnit.SECONDS);
driver.get("https://www.google.com");
driver.close();
driver.quit();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static void main(String[] args) {
SeleniumWebDriver myobject = new SeleniumWebDriver();
myobject.invokeBrowser();
}
}
Is there a need for me to fix it and how? Thank you.
If you wanted to stop this warning message in the console you need to pass --silent argument to chromedriver to stop console message. you can achieve this using 'withSilent(true)' method
Launch chromedriver using chromedriverservice as shown in below sample code
ChromeDriverService cdservice=new ChromeDriverService.Builder().usingDriverExecutable(new File("/path/to/chromedriver.exe"))
.withLogFile(new File("/path/to/chromedriver.log"))
.withSilent(true)
.usingAnyFreePort()
.build();
WebDriver driver = new ChromeDriver(cdservice);
driver.get("http://www.google.com");

Trying to run an eclipse JAVA program in Sauce Labs. But getting an issue with constructor and remote webdriver.

Written below code to run an eclipse program in Sauce Labs. Workflow is showing an issue "The constructor Remote WebDriver(String, DesiredCapabilities) is undefined".
Still I tried to run the program then below issue came.
Exception in thread "main" java.lang.Error: Unresolved compilation problems:
The constructor RemoteWebDriver(URL, DesiredCapabilities) is undefined
The constructor URL(String) is undefined at sauceprog.main(sauceprog.java:40)
CODE:
import java.net.MalformedURLException;
import org.openqa.selenium.By;
import org.openqa.selenium.Keys;
import org.openqa.selenium.remote.CommandExecutor;
import org.openqa.selenium.remote.DesiredCapabilities;
import org.openqa.selenium.remote.RemoteWebDriver;
import com.gargoylesoftware.htmlunit.javascript.host.URL;
public class sauceprog
{
public static void main(String[] args) throws InterruptedException, MalformedURLException
{
String browser = "safari-saucelabs";
String URL = "https://rpautomation4:27763475-7193-4984-8074-a4fe2f9982f7#ondemand.saucelabs.com:443/wd/hub";
DesiredCapabilities caps = null;
switch(browser.toLowerCase())
{
case "internetexplorer-win-saucelabs":
caps = DesiredCapabilities.internetExplorer();
caps.setCapability("platform", "Windows 10");
caps.setCapability("version", "11.103");
caps.setCapability("recordVideo", "false");
caps.setCapability("screenResolution", "1024x768");
break;
case "chrome-win-saucelabs":
caps = DesiredCapabilities.chrome();
caps.setCapability("platform", "Windows 8");
caps.setCapability("version", "69.0");
caps.setCapability("recordVideo", "false");
break;
case "firefox-win-saucelabs":
caps = DesiredCapabilities.firefox();
caps.setCapability("platform", "Windows 8");
caps.setCapability("version", "62.0");
caps.setCapability("recordVideo", "false");
default:
System.out.println("you passed incorrect values. Please check next time");
}
RemoteWebDriver driver = new RemoteWebDriver(URL,caps);
driver.get("https://www.google.com");
driver.findElement(By.name("q")).sendKeys("selenium");
Thread.sleep(2000);
driver.findElement(By.name("q")).sendKeys(Keys.ENTER);
Thread.sleep(5000);
driver.quit();
}
}
You are using an incorrect import statement. Ideally, your program should use import java.net.URL; instead of import com.gargoylesoftware.htmlunit.javascript.host.URL;
I have posted the complete updated code snippet below:
import org.openqa.selenium.By;
import org.openqa.selenium.Keys;
import org.openqa.selenium.remote.DesiredCapabilities;
import org.openqa.selenium.remote.RemoteWebDriver;
import java.net.MalformedURLException;
import java.net.URL;
public class sauceprog
{
public static void main(String[] args) throws InterruptedException, MalformedURLException
{
String browser = "safari-saucelabs";
String URL = "https://<sauce_user>:<key>#ondemand.saucelabs.com:443/wd/hub";
DesiredCapabilities caps = null;
switch(browser.toLowerCase())
{
case "internetexplorer-win-saucelabs":
caps = DesiredCapabilities.internetExplorer();
caps.setCapability("platform", "Windows 10");
caps.setCapability("version", "11.103");
caps.setCapability("recordVideo", "false");
caps.setCapability("screenResolution", "1024x768");
break;
case "chrome-win-saucelabs":
caps = DesiredCapabilities.chrome();
caps.setCapability("platform", "Windows 8");
caps.setCapability("version", "69.0");
caps.setCapability("recordVideo", "false");
break;
case "firefox-win-saucelabs":
caps = DesiredCapabilities.firefox();
caps.setCapability("platform", "Windows 8");
caps.setCapability("version", "62.0");
caps.setCapability("recordVideo", "false");
default:
System.out.println("you passed incorrect values. Please check next time");
}
RemoteWebDriver driver = new RemoteWebDriver(new URL(URL),caps);
driver.get("https://www.google.com");
driver.findElement(By.name("q")).sendKeys("selenium");
Thread.sleep(2000);
driver.findElement(By.name("q")).sendKeys(Keys.ENTER);
Thread.sleep(5000);
driver.quit();
}
}
Also, I would suggest you update your sauce username and key if not already done. Since you posted the username and key publicly, anyone can run their tests on your account using the same.

How to register multiple nodes to the hub in selenium grid

Need to register multiple nodes to the hub, Any help in this regards will be appreciated.Selenium grid to be performed with the same driver object.
This is how my code looks like.
Deriving the class using RemoteWebDriver for Hub instance.
import java.net.URL;
import java.util.Arrays;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.Platform;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.ie.InternetExplorerDriver;
import org.openqa.selenium.remote.CapabilityType;
import org.openqa.selenium.remote.DesiredCapabilities;
import org.openqa.selenium.remote.RemoteWebDriver;
import com.project.pages.ExcelConstants;
public class DriverInitializer {
private WebDriver driver = null;
public WebDriver getWebDriverFactory() {
return this.driver;
}
/**
* Returns WebDriver Instance Depending on Parameters browser and Grid d
*
* #param browser
* #param grid
* #return
*/
public WebDriver getDriver(String browser, String grid) {
if (grid.equals("y")) {
getWebDriverRemote(browser);
} else if (grid.equals("n")) {
getWebDriverLocal(browser);
}
return driver;
}
/**
* Creates Local WebDriver Instance
*
* #param browser
* #return
*/
public WebDriver getWebDriverLocal(String browser) {
try {
if (browser.equalsIgnoreCase("chrome")) {
System.setProperty("webdriver.chrome.driver",
System.getProperty("user.dir")
+ "\\Drivers\\chromedriver.exe");
ChromeOptions options = new ChromeOptions();
options.setExperimentalOption("excludeSwitches",
Arrays.asList("ignore-certificate-errors"));
driver = new ChromeDriver(options);
return driver;
}
if (browser.equalsIgnoreCase("ie")) {
System.setProperty("webdriver.ie.driver",
System.getProperty("user.dir")
+ "\\drivers\\IEDriverServer.exe");
DesiredCapabilities cap = DesiredCapabilities
.internetExplorer();
cap.setCapability(
InternetExplorerDriver.UNEXPECTED_ALERT_BEHAVIOR,
"accept");
cap.setCapability("nativeEvents", true);
cap.setCapability(InternetExplorerDriver.INITIAL_BROWSER_URL,
ExcelConstants.TEST_URL_2);
cap.setCapability(CapabilityType.ACCEPT_SSL_CERTS, true);
cap.setCapability(
InternetExplorerDriver.INTRODUCE_FLAKINESS_BY_IGNORING_SECURITY_DOMAINS,
true);
return driver = new InternetExplorerDriver(cap);
}
if (browser.equals("firefox")) {
System.setProperty("webdriver.gecko.driver",
System.getProperty("user.dir")
+ "\\Drivers\\geckodriver.exe");
// Extra code added
DesiredCapabilities capabilities = new DesiredCapabilities();
capabilities.setCapability("acceptInsecureCerts", true);
// Extra code ended
return driver = new FirefoxDriver(capabilities);
}
} catch (Exception e) {
System.out.println(e.getMessage());
}
return driver;
}
/**
* Creates Remote WebDriver Instance
*
* #param browser
* #return
*/
public WebDriver getWebDriverRemote(String browser) {
DesiredCapabilities cap = null;
try {
if (browser.equals("ie")) {
cap = DesiredCapabilities.internetExplorer();
cap.setCapability(
InternetExplorerDriver.UNEXPECTED_ALERT_BEHAVIOR,
"accept");
cap.setCapability(InternetExplorerDriver.INITIAL_BROWSER_URL,
ExcelConstants.TEST_URL_2);
cap.setCapability("nativeEvents", true);
cap.setBrowserName("internet explorer");
cap.setPlatform(Platform.ANY);
}
if (browser.equals("firefox")) {
cap = DesiredCapabilities.firefox();
cap.setCapability(
InternetExplorerDriver.UNEXPECTED_ALERT_BEHAVIOR,
"accept");
cap.setBrowserName("firefox");
cap.setPlatform(Platform.ANY);
}
if (browser.equals("chrome")) {
cap = DesiredCapabilities.chrome();
cap.setBrowserName("chrome");
cap.setPlatform(Platform.WINDOWS);
}
driver = new RemoteWebDriver(new URL(ExcelConstants.NODE_URL_1), cap);
} catch (Exception e) {
System.out.println(e.getMessage());
}
return driver;
}
public static void main(String[] args) {
DriverInitializer di = new DriverInitializer();
di.getWebDriverRemote("chrome");
}
/**
* Implicit Wait
*/
public void waitForPageToLoad(WebDriver driver) {
driver.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS);
}
/**
* Maximizes the window
*/
public void maximizeWindow(WebDriver driver) {
driver.manage().window().maximize();
}
}
I tried using the thread class but unable to implement it using the concept.
download selenium server stand alone jar from here
after that follow below step
1- start hub using below command
java -jar "your selenium serverstand-alone.jar file path here" -role hub
2- now register your first node with hub-
java -jar "your selenium-server-stand-alone.jar file path here" -role node -hub http://localhost:4444/grid/register -port 5556 -browser "browserName=chrome, maxInstances=5"
3- now start 3rd, 4th etc. by just changing -port and browser value
java -jar "your selenium-server-stand-alone.jar file path here" -role node -hub http://localhost:4444/grid/register -port 5558 -browser "browserName=firefox, maxInstances=5"
to execute on node using selenium server use RemoteWebDriver instead of firefox or chrome driver
for more details description follow below tutorial
https://www.guru99.com/introduction-to-selenium-grid.html

Selenium Ebay Script

I have logged into Ebay and want to click the hyperlink of 'My collections' which is under "G'day [username]". The issue is now I can not find the element of 'My collections'. The error message is "Unable to locate element: (//li[#id='gh-ucol']/a)
Please refer to the below steps how I replicate:
Open Ebay via Firefox
Click Log in hyperlink
Enter the user name password then click log in button
Click "G'day [username]"
Select 'My Collection' from the droplist
This is my Selenium Java Script:
import org.openqa.selenium.By;
import org.openqa.selenium.NoSuchElementException;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
public class KevinTest {
public static void main(String[] args) throws InterruptedException{
WebDriver driver = new FirefoxDriver();
driver.get("http://www.ebay.com.au");
driver.manage().window().maximize();
Thread.sleep(20);
driver.findElement(By.linkText("Sign in")).click();
Thread.sleep(100);
driver.findElement(By.xpath("(//input[#placeholder='Email or username'])[2]")).sendKeys("my#username");
driver.findElement(By.xpath("(//input[#placeholder='Password'])[1]")).sendKeys("mypassword");
driver.findElement(By.id("sgnBt")).click();
boolean tf;
try {
driver.findElement(By.id("errf")).getText();
tf = true;
}catch(NoSuchElementException e) {
tf = false;
}
if (tf == true) {
System.out.println("Incorrect Password");
driver.close();
}else {
System.out.println("Log in successfully");
}
driver.findElement(By.id("gh-eb-u")).click();
Thread.sleep(100);
driver.findElement(By.xpath("(//*[#id='gh-ucol']/a)")).click();
}}
Its a good practice to use implicit wait after initiating the driver.
WebDriver driver = new FirefoxDriver();
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
Use the below id for the 'Click "G'day [username]'.
driver.findElement(By.id("gh-ug")).click();
Use the below xpath for collection.
driver.findElement(By.id("//*[#id="gh-ucol"]/a")).click();
Since we have used implicit wait you can remove all other thread.sleeps. Hope this helps. Thanks.

Setup proxy in Firefox browser via marionette driver

Firefox 47 and above do not support Selenium Webdriver. I tried to use a Marionette driver to start my tests via Firefox.
But my settings in firefox-profile (proxy must set to network.proxy.type = 4, auto-detect) is no longer applied to Firefox config (Firefox opens but all settings set by default) and my tests do not work without the right PROXY configuration.
How can I setup proxy in Firefox browser via a Marionette driver?
The old tricks with firefoxProfile or Proxy class do not work any more. All you have to do is pass through requiredCapabilities a JSON with the new Marionette proxy format:
[{proxy={"proxyType":"MANUAL","httpProxy":"host.proxy","httpProxyPort":80,"sslProxy":"host.proxy","sslProxyPort":80}}]
No more "proxyHost:proxyPort" format, but httpProxy=host, httpProxyPort=port.
JsonObject json = new JsonObject();
json.addProperty("proxyType", "MANUAL");
json.addProperty("httpProxy", aHost);
json.addProperty("httpProxyPort", aPort);
json.addProperty("sslProxy", aHost);
json.addProperty("sslProxyPort", aPort);
required.setCapability("proxy", json);
driver = new FirefoxDriver(service, cap, required);
Here is all the code:
import java.io.File;
import java.io.IOException;
import org.apache.commons.lang.SystemUtils;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxBinary;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.firefox.GeckoDriverService;
import org.openqa.selenium.remote.DesiredCapabilities;
import com.google.common.collect.ImmutableMap;
import com.google.gson.JsonObject;
public class TestProxy
{
public static void main(String[] args)
{
if (args.length == 0)
{
System.out.println("usage: IP port");
System.exit(-1);
}
String proxyServer = args[0];
int proxyPort = Integer.parseInt(args[1]);
try
{
TestProxy test = new TestProxy();
test.TestDriver(proxyServer, proxyPort);
} catch (IOException e)
{
e.printStackTrace();
}
}
private void TestDriver(String aHost, int aPort) throws IOException
{
WebDriver driver = null;
GeckoDriverService service = null;
if (SystemUtils.IS_OS_LINUX)
{
FirefoxBinary firefoxBinary = new FirefoxBinary(new File("/home/ubuntu/firefox/firefox"));
service = new GeckoDriverService.Builder(firefoxBinary)
.usingDriverExecutable(new File("/usr/bin/geckodriver"))
.usingAnyFreePort()
.usingAnyFreePort()
.withEnvironment(ImmutableMap.of("DISPLAY",":20"))
.build();
service.start();
}
else if (SystemUtils.IS_OS_WINDOWS)
{
FirefoxBinary firefoxBinary = new FirefoxBinary(new File("C:\\Program Files\\Mozilla Firefox\\firefox.exe"));
service = new GeckoDriverService.Builder(firefoxBinary)
.usingDriverExecutable(new File("C:\\Windows\\geckodriver.exe"))
.usingAnyFreePort()
.usingAnyFreePort()
.build();
service.start();
}
else
{
System.out.println("Unknown operation system");
System.exit(-1);
}
DesiredCapabilities cap = DesiredCapabilities.firefox();
DesiredCapabilities required = new DesiredCapabilities();
JsonObject json = new JsonObject();
json.addProperty("proxyType", "MANUAL");
json.addProperty("httpProxy", aHost);
json.addProperty("httpProxyPort", aPort);
json.addProperty("sslProxy", aHost);
json.addProperty("sslProxyPort", aPort);
required.setCapability("proxy", json);
driver = new FirefoxDriver(service, cap, required);
driver.navigate().to("https://api.ipify.org/?format=text");
System.out.println(driver.getPageSource());
driver.quit();
}
}
https://github.com/SeleniumHQ/selenium/issues/2963
https://github.com/mozilla/geckodriver/issues/97#issuecomment-255386464