Selenium - How to get a local WebDriver by Browser name - selenium

A RemoteWebDriver could be instantiated via browsername like "firefox" via DesiredCapabilties object.
But how to get a local driver like "FireFoxDriver" with browser name?
My use case is as follows: the browsers to be tested are specified via properties in an external text file. with another property the grid url is set. if grid url is set to "local" i want to run the tests local on the browsers set in text file.
(how) is this possible?

Sure. Something in the way of this?
public static void main(String[] args) {
WebDriver driver = openBrowser(args[0]);
// now work with driver as usual
}
public static WebDriver openBrowser(String browserName) {
if ((browserName == null) || (browserName.trim().isEmpty())) {
throw new IllegalArgumentException("No browser name found.");
}
// works with Java 7, on Java < 7, you have to write an if-else block instead
switch (browserName.toLowerCase()) {
case "ff": // fall through
case "firefox":
return new FirefoxDriver();
case "ie": // fall through
case "iexplore": // fall through
case "internet explorer":
return new InternetExplorerDriver();
default:
throw new IllegalArgumentException("No valid browser name found.");
}
}

I can suggest a hack. Launch selenium-server on your local machine and then you can use remotewebdriver with host url as http://localhost:4444/wd/hub.
This way you would be able to use same remote driver and external text file to control your tests on the local machine.

Related

Selenium JUnit tests not running org.openqa.selenium.NoSuchSessionException: Session ID is null. Using WebDriver after calling quit()?

I have created a java/selenium/cucumber automation framework with 4 feature files each testing different functional area's.
I can run each of these within Eclipse as feature files and they all run fine.
However I am trying to figure out how I can run them all as a JUnit test so that I can generate the extent reports.
I run the mainRunner class as a Junit test like ..
The first feature runs fine but then the next three do not. A chrome browser is opened for each of these but
the site is not navigated to. The error
'org.openqa.selenium.NoSuchSessionException: Session ID is null. Using WebDriver after calling quit()?'
is shown in the console logs.
So is this issue to do with how I have set my feature files up to use the startBrowser, initBrowser and closeBrowser methods. Which are
defined in a seperate class 'BrowserInitTearDownStepDefinitions'?
All my feature files look like ..
Feature: Update a Computer in Database
-- left out details
#StartBrowser
Scenario: Start browser session
When I initialize driver
Then open browser
#MyTest4
Scenario Outline: Update a computer
-- left our details
Examples:
-- left out details
#CloseBrowser
Scenario: Close the browser
Then close browser
I have had a look at the other posts related to this message that reference the same error, but can't see a clear cut solution.
As the error would indicate I seem to be quitting the driver but then not reinitialising it for the next test. Although Im not sure why this
would be the case given that each feature file has the #StartBrowser and #CloseBrowser tags which should execute these methods. Below is my BrowserInitTearDownStepDefinitions class.
public class BrowserInitTearDownStepDefinitions {
//Initialises Chrome browser
#When("^I initialize driver$")
public void initializeDriver() {
System.out.println("initializeDriver runs");
System.setProperty("webdriver.chrome.driver","C:\\xxxx\\CucumberAutomationFramework\\src\\test\\java\\cucumberAutomationFramework\\resources\\chromedriver.exe");
WebDriverUtils.setDriver(new ChromeDriver());
}
//Opens Chrome browser and clicks in search input box
#Then("^open browser$")
public void openBrowser() {
System.out.println("Open Browser runs");
WebDriver driver = WebDriverUtils.getDriver();
driver.manage().window().maximize();
driver.manage().timeouts().pageLoadTimeout(60, TimeUnit.SECONDS);
driver.manage().timeouts().setScriptTimeout(60, TimeUnit.SECONDS);
driver.get("https://computer-database.gatling.io/computers");
}
//Closes browser after all scenarios run and deletes cookies
#Then("^close browser$")
public void closeBrowser() {
System.out.println("Close Browser runs");
WebDriver driver = WebDriverUtils.getDriver();
driver.manage().deleteAllCookies();
driver.quit();
driver =null;
}
}
I create a new instance of the webdriver within my stepDefs file with ..
WebDriver driver = WebDriverUtils.getDriver()
The webdriver utils class code is ..
package cucumberAutomationFramework.utilityClasses;
import org.openqa.selenium.WebDriver;
public class WebDriverUtils {
private static WebDriver driver;
public static void setDriver(WebDriver webDdriver) {
if (driver == null) {
driver = webDdriver;
}
}
public static WebDriver getDriver() {
if (driver == null) {
throw new AssertionError("Driver is null. Initialize driver before calling this method.");
}
return driver;
}
}
Any advice would be much appreciated. Thanks.

Can selenium test run without using System.setProperty in the code?

I am able to run the selenium test in our project without using System.setProperty. Not sure how it works, we have set the environment Path variable with value "C:\Akash\Drivers" where all the drivers are stored. Can anyone explain how/ this works without setting up chrome path?
public class SeleniumTest {
public static void main(String[] args) throws MalformedURLException {
// TODO Auto-generated method stub
localSettings();
}
public static void localSettings() {
// System.setProperty("webdriver.chrome.driver", "C:\\Akash\\Drivers\\chromedriver.exe");
WebDriver driver = new ChromeDriver();
driver.get("https://www.google.com");
}
}
Please Refer official explanation given Seleniumhq & Chrome,
How it retrieves and Work with Environment Variables :
WebDriver works with Chrome through the chromedriver binary. You need to have both chromedriver and a version of chrome browser installed. chromedriver needs to be placed somewhere on your system’s path in order for WebDriver to automatically discover it. The Chrome browser itself is discovered by chromedriver in the default installation path. These both can be overridden by environment variables.
Provided by Seleniumhq, Blog Link : Click Here
Chrome Driver Setup Provisions:
Provided by Chrome, Blog Link : Click Here

selenium grid connction with autoit not working?

selenium grid connection with auto it not working ?
#daluudaluu/PartialSeleniumGridIntegrationWithAutoItExample.java
Last active a year ago
Embed
Download ZIP
Code Revisions 2 Forks 1
Partial Selenium Grid integration support with tools like AutoIt, Sikuli, etc.
Raw
PartialSeleniumGridIntegrationWithAutoItExample.java
import static org.junit.Assert.*;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.openqa.selenium.*;
import org.openqa.selenium.remote.*;
import java.net.URL;
public class DemoTest {
public WebDriver driver;
public DesiredCapabilities capabilities;
#Before
public void setUp() throws Exception {
capabilities = DesiredCapabilities.firefox();
driver = new RemoteWebDriver(new URL("http://localhost:4444/wd/hub" ), capabilities);
}
#After
public void tearDown() throws Exception {
driver.quit();
}
#Test
public void test() throws Exception {
// Use RemoteWebDriver, grab actual node host info
driver.get("http://www.google.com");
String sessionId = ((RemoteWebDriver) driver).getSessionId().toString();
//grid info extractor from: https://gist.github.com/krmahadevan/1766772
String nodeHost = GridInfoExtracter.getHostNameAndPort("localhost", 4444, sessionId)[0];
System.out.println("Extracted hostname: "+nodeHost);
// Now use node host info to handle running AutoIt on that specific node, assuming all needed files deployed to all nodes
// Case 1 - PSExec.exe from Windows host (that is executing this Selenium code) to Selenium node that is Windows host
//String psexecCmd = "C:\\LocalMachinePathTo\\psexec.exe \\\\%s -u %s -p %s -i C:\\GridNodeMachinePathTo\\autoitCompiledScript.exe";
//Process p = Runtime.getRuntime().exec(String.format(psexecCmd,nodeHost,"jdoe","hisPassword"));
//p.waitFor();
// Case 2 - winexe from *nix host (that is executing this Selenium code) to Selenium node that is Windows host
// Example reference: http://secpod.org/blog/?p=661
//String winexeCmd = "/LocalMachinePathTo/winexe -U domainName/jdoe%hisPassword //"+nodeHost+" C:\\GridNodeMachinePathTo\\autoitCompiledScript.exe";
//Process p = Runtime.getRuntime().exec(winexeCmd);
//p.waitFor();
// Case 3 - have SSH installed on Windows-based Selenium nodes, now just connect to node host via SSH to run a command, i.e. execute AutoIt script binary
// no sample code given for Java, but maybe this gives you ideas on Java SSH connection:
// http://stackoverflow.com/questions/995944/ssh-library-for-java
// Case 4 - if you have implemented a custom web service (XML-RPC/SOAP/REST) for AutoIt that listens for requests/commands
// just connect to it via (Java) HTTP library to "http://"+nodeHost+"/someWebServicePath/someCommand" (via GET or POST)
// details not covered, this is just an example. Most people won't be taking this route due to customization & complexity in
// building the web service first
// Case 5 - using AutoItDriverServer that is also running on Selenium nodes
//DesiredCapabilities autoitCapabilities = new DesiredCapabilities();
//autoitCapabilities.setCapability("browserName", "AutoIt");
//WebDriver autoitDriver = new RemoteWebDriver(new URL("http://"+nodeHost+":4723/wd/hub"), autoitCapabilities);
//autoitDriver.findElement(By.id("133")).click();
//and whatever other AutoItX commands to call that you normally have in the AutoIt script that you compile into binary
//for more ideas on AutoIt commands issued as WebDriver commands with respect to Selenium integration, see:
//https://github.com/daluu/AutoItDriverServer/blob/master/sample-code/SeleniumIntegrationWithAutoItDriver.py
//or if you are old school, and want to do that same approach even with AutoItDriverServer,
// assuming you have first set AutoItScriptExecuteScriptAsCompiledBinary to True in autoit_options.cfg file before starting AutoItDriverServer:
//((JavascriptExecutor) autoitDriver).executeScript("C:\\GridNodeMachinePathTo\\autoitCompiledScript.exe");
// Case for Sikuli integration, using https://github.com/enix12enix/sikuli-remote-control
//RemoteScreen rs = new RemoteScreen(nodeHost);
//rs.setMinSimilarity(0.9);
//rs.click("D://test.png");
}
}

Cross browser test

I have to do login to an application with two different browsers (IE & FF) and hence I tried to do cross browser test. When the URL gets passed to IE, I am getting link as "Continue to this website not recommended", whereas the same link will not be displayed in FF. In the below if I use this statement driver.findElement(By.id("overridelink")).click(); then it works fine in IE but failing in firefox since there wont be any link in FF.
please let me know the possible where one script should run in both the browsers. Below is the script which am trying
#Test
#Parameters("browser")
public void verifypagetitle(String browsername) {
if(browsername.equalsIgnoreCase("IE"))
{
System.setProperty("webdriver.ie.driver",
"D:\\2.53.1\\IEDriverServer.exe");
driver = new InternetExplorerDriver();
}
else if (browsername.equalsIgnoreCase("firefox"))
{
System.setProperty("webdriver.firefox.bin",
"C:\\Program Files\\Mozilla Firefox\\firefox.exe");
driver = new FirefoxDriver();
}
driver.get("URL");
driver.manage().window().maximize();
driver.findElement(By.id("overridelink")).click();
driver.findElement(By.id("j_username")).sendKeys("userid");
driver.findElement(By.id("j_password")).sendKeys("pwd");
driver.findElement(By.id("j_password")).submit();
This is most likely caused by the IE security level. In my experience if I change it to Low, the warning is not present. You can try and see if this will solve the issue in your case.
Another solution is to add conditional logic to check the browser being used. Something like this:
Capabilities cap = ((RemoteWebDriver) browserDriver).getCapabilities();
String browsername = cap.getBrowserName();
// This block to find out if it is IE
if ("internet explorer".equalsIgnoreCase(browsername)) {
driver.findElement(By.id("overridelink")).click();
}

WebDriver not opening URL

I'm very new to selenium so I'm having trouble spotting the problem with my code. I'm using a webDriver backed selenium object, it starts the driver but never opens the URL and the driver just closes after a few moments. The last time this happened to me it was just because I had left "http" out of the URL. So what's causing it this time?
public void testImages() throws Exception {
Selenium selenium = new WebDriverBackedSelenium(driver, "http://www.testsite.com/login");
System.out.println(selenium.getXpathCount("//img"));
}
The setup looks like:
public void setUp() throws Exception {
System.setProperty("webdriver.chrome.driver", "C:\\Users\\User1\\Desktop\\chromedriver_win_16.0.902.0\\chromedriver.exe");
driver = new ChromeDriver();
Thread.sleep(2000);
}
The teardown method just consists of driver.close().
I'm using selenium 2.14 and the testNG Eclipse plug-in.
You might need to do the following
selenium.open("www.testsite.com/login");
Check out this example from the selenium site:
// You may use any WebDriver implementation. Firefox is used here as an example
WebDriver driver = new FirefoxDriver();
// A "base url", used by selenium to resolve relative URLs
String baseUrl = "http://www.google.com";
// Create the Selenium implementation
Selenium selenium = new WebDriverBackedSelenium(driver, baseUrl);
// Perform actions with selenium
selenium.open("http://www.google.com");
selenium.type("name=q", "cheese");
selenium.click("name=btnG");
// Get the underlying WebDriver implementation back. This will refer to the
// same WebDriver instance as the "driver" variable above.
WebDriver driverInstance = ((WebDriverBackedSelenium) selenium).getUnderlyingWebDriver();
//Finally, close the browser. Call stop on the WebDriverBackedSelenium instance
//instead of calling driver.quit(). Otherwise, the JVM will continue running after
//the browser has been closed.
selenium.stop();
link to selenium
You would need to add driver.get(url) like below.
public void setUp() throws Exception {
System.setProperty("webdriver.chrome.driver", "C:\\Users\\User1\\Desktop\\chromedriver_win_16.0.902.0\\chromedriver.exe");
driver = new ChromeDriver();
driver.get("http://www.testsite.com/login");
}