Pages

Saturday, 19 May 2012

How to check the presence of Alert (isAlertPresent) using WebDriver?

Below method will return true if the alert got displayed:

public boolean isAlertPresent() {

  boolean presentFlag = false;

  try {

   // Check the presence of alert
   Alert alert = driver.switchTo().alert();
   // Alert present; set the flag
   presentFlag = true;
   // if present consume the alert
   alert.accept();

  } catch (NoAlertPresentException ex) {
   // Alert not present
   ex.printStackTrace();
  }

  return presentFlag;

 }
Note - Thank you Ganesh S for asking this query.

Friday, 9 March 2012

How can I execute Javascript?

We can execute Javascript by casting the WebDriver instance to a JavascriptExecutor:

//Instantiate any WebDriver; Eg. Firefox
 WebDriver driver = new FirefoxDriver();
 driver.get("http://seleniumwebdriverfaq.tumblr.com/");
 //Casting the WebDriver instance to a JavascriptExecutor
 JavascriptExecutor js = (JavascriptExecutor) driver;
 //Execute the JavaScript - Eg. to get the page title
 js.executeScript("return document.title");
 //Print the out put
 System.out.println("Page title from Java script: "
      +js.executeScript("return document.title"));
 System.out.println("Page title from driver.getTitle() : "
      +driver.getTitle());
 //JUnit Assertion
 Assert.assertEquals(js.executeScript
    ("return document.title"),driver.getTitle());

How to take screenshot of the test page?

We can take entire page screenshot by following code:


   //Instantiate any WebDriver; Eg. Firefox
WebDriver driver = new FirefoxDriver();
driver.get("http://seleniumwebdriverfaq.tumblr.com/");
//Get the screenshot as file
File scrFile = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
// Copy the screenshot to your file system
FileUtils.copyFile(scrFile, new File("c:\screenshots\screenshot.png"));

How can I start Firefox with add-ons installed?

Create a Firefox profile and add required add-ons. 


Take ‘Firebug’ as an example, save the Firebug XPI into the C:FF_addons folder as firebug.xpi (Download XPI file from Firebug download page, right-click on the “Download Now” and save as C:FF_addonsfirebug.xpi).


Then create a Firefox profile and add Firebug add-on while instantiating FirefoxDriver as below:


   String firebugFilePath = "C:\FF_addons\firebug.xpi";
FirefoxProfile profile = new FirefoxProfile();
profile.addExtension(new File(firebugFilePath));
// Add more FF addons if required
WebDriver driver = new FirefoxDriver(profile);

Thursday, 8 March 2012

How can I handle alert dialog box?

Below method will handle the alert dialog displayed and also it will return the alert message displayed.

public String getAlert() { 
     Alert alert = driver.switchTo().alert(); 
     String alertMsg = alert.getText();
     alert.accept();
     return alertMsg; } 

Wednesday, 7 March 2012

Why am getting security message while instantiating IE WebDriver?

Security Message:“Protected Mode must be set to the same value (enabled or disabled) for all zones.”


Solutions 1:


Set manually the protected mode to the same value (enabled or disabled) for all zones in ‘Internet Options’ —> ‘Security’ Tab.


Solution 2:


Set a capability while instantiating IE driver, as shown below:


 DesiredCapabilities capability=DesiredCapabilities.internetExplorer();
capability.setCapability(
InternetExplorerDriver.INTRODUCE_FLAKINESS_BY_
IGNORING_SECURITY_DOMAINS, true);
WebDriver webdriver = new InternetExplorerDriver(capability);

How can I Kill the WebDriver instance?

The quit() method will kill the WebDriver instance.


That is,


//If "driver" is an instance of WebDriver;Then to kill the instance:
driver.quit();

How can I read background-color of an element?

We can get/read the background-color of an element by using getCssValue() method of WebDriver:


driver.get("http://www.google.co.in/");
String color = driver.findElement(By.name("btnK")).getCssValue("background-color");

System.out.println("The background color of Google search button"+color);

How can I get required attribute value of the element?

We can get the specific attribute of an element by using getAttribute() method:


//Find the element
WebElement gButton = driver.findElement(By.name("btnK"));
// Get the required attribute value
String gButtonStyle = gButton.getAttribute("style");

System.out.println("The Google search button's style attribute value is "+gButtonStyle);

The getAttribute() method gets the value of an element attribute specified.


Suppose, you want to get the value/content of a text field then, specify the attribute name as “value” (instead off “style”).

How can I get the text of the element?

Using getText() method, we can get the text of the element.


That is,


WebElement gButton = driver.findElement(By.name("btnK"));
String gButtonText = gButton.getText();
System.out.println("The Google search button's display text is "+gButtonText);

The getText() method gets the text of an element. This uses either the textContent (Mozilla-like browsers) or the innerText (IE-like browsers) of the element, which is the rendered text shown to the user.

How can I get title of the window?

We can get the title of the window by using getTitle() method:


String title = driver.getTitle(); 
System.out.println("Title of the page is "+title);

Monday, 5 March 2012

How can I move backwards or forwards in browser's history?

We can move backwards and forwards in browser’s history as below:


//To go backward
driver.navigate().back();
//To go forward
driver.navigate().forward();

Sunday, 4 March 2012

How can I use/emulate Selenium RC with WebDriver?

The Java version of WebDriver provides an implementation of the Selenium-RC API. It allows those who have existing test suites using the Selenium-RC API to use WebDriver under the covers.


Example:


// 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).getWrappedDriver();

//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();

How can I check the presence of WebElement on page?

We can check the presence of WebElement on page by implementing custom isElementPresent method as below:


	protected boolean isElementPresent(By by) {
try {
driver.findElement(by);
return true;
} catch (NoSuchElementException e) {
return false;
}
}

This method will return true, if the WebElement with ‘by’ available otherwise returns false.

Sunday, 26 February 2012

I would like to know all the frames available on the page, how can I get that?

We can get a list of frame names available on a page as below:


	//Make sure you are in default frame
driver.switchTo().defaultContent();
List framesetList=driver.findElements(By.tagName("frame"));
if(framesetList.size()>0){
for(WebElement framename :framesetList){
System.out.println("Frame with name:" + framename.getAttribute("name")+" found.");
}
}
else {
System.out.println("No frame found");
}

How can I switch WebDriver control between Frames?

If the application under test contains frames, then we need to switch the WebDriver control to that frame before interacting with the element inside the frame.


We can switch to frame either with it’s name/id or by specifying frame index.


Sample code : By using frame name


driver.switchTo().frame("frameName");

By index (Zero-based):


driver.switchTo().frame(1);

And to come back to default frame:

driver.switchTo().defaultContent();

Sunday, 19 February 2012

How can I switch WebDriver control to new window?

To switch latest window opened use below code:

for(String winHandle : driver.getWindowHandles()){
    driver.switchTo().window(winHandle);
}

Sampe code:


 package test;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;

public class SwithcToNewWindow {

public static void main(String[] arg) {

// Instantiate the FirefoxDriver
WebDriver driver = new FirefoxDriver();

// Visit the Selenium-WebDriver FAQ site
driver.get("http://seleniumwebdriverfaq.tumblr.com/");

// Print the title of the page - It should print
// "Selenium-WebDriver FAQ's"
System.out.println("Title of the page before - switchingTo: " + driver.getTitle());

//Now click on RSS button; it will open in new window
driver.findElement(By.xpath("//a[text()='RSS']")).click();

//Switch to newly opened window -RSS and get the page titele
for(String winHandle : driver.getWindowHandles()){
driver.switchTo().window(winHandle);
}
System.out.println("Title of the page after - switchingTo: " + driver.getTitle());

// Close the browser window
driver.close();

// Quit the driver
driver.quit();
}
}

Tuesday, 14 February 2012

Why I am getting "java.lang.IllegalStateException" while instantiating Chrome driver?

Sample error log:


Exception in thread "main" java.lang.IllegalStateException: The path to the chromedriver executable must be set by the webdriver.chrome.driver system property; for more information, see http://code.google.com/p/selenium/wiki/ChromeDriver. The latest version can be downloaded from http://code.google.com/p/chromium/downloads/list
    at com.google.common.base.Preconditions.checkState(Preconditions.java:172)
    at org.openqa.selenium.chrome.ChromeDriverService.createDefaultService(ChromeDriverService.java:103)
    at org.openqa.selenium.chrome.ChromeDriver.<init>(ChromeDriver.java:86)
    at tests.ChromeTest.main(ChromeTest.java:29)


To solve this problem, you have to set chromedriver executable path by the “webdriver.chrome.driver” system property.


That is, in java you can set that as below:


System.setProperty("webdriver.chrome.driver","C:\path\to\<<chromedriver_win_...>>\chromedriver.exe");

// Then Instantiate the ChromeDriver
WebDriver driver = new ChromeDriver();

Note - You can download latest ChromeDriver binary from here

Wednesday, 8 February 2012

How can I instantiate OperaDriver?

The OperaDriver can be instantiated as below:


WebDriver driver = new OperaDriver(); // Instantiate the class - com.opera.core.systems.OperaDriver

Sample code(Java Binding - Windows):


package tests;

import org.openqa.selenium.WebDriver;
import com.opera.core.systems.OperaDriver;

public class OperaDriverSample {

public static void main(String[] argv) throws Exception {

//Opera exe should be in %PROGRAMFILES%Operaopera.exe

// Instantiate the OperaDriver
WebDriver driver = new OperaDriver();

// Visit the Selenium-WebDriver FAQ site
driver.get("http://seleniumwebdriverfaq.tumblr.com/");

// Print the title of the page - It should print "Selenium-WebDriver FAQ's"
System.out.println("Title of the page is: " + driver.getTitle());

//Close the browser window
driver.close();

//Quit the driver
driver.quit();

}

}

How can I instantiate ChromeDriver?

The ChromeDriver can be instantiated as below:


WebDriver driver = new ChromeDriver(); // Instantiate the class - org.openqa.selenium.chrome.ChromeDriver

Sample code(Java Binding - Windows):


package tests;

import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeDriverService;

public class ChromeDriverSample {

public static void main(String[] argv) throws Exception {

// For ChomeDriver, Need to Set 'webdriver.chrome.driver' property; if Chrome server binary (chromedriver.exe) file
//path is not mentioned in 'PATH'

//Download latest ChromeDriver binary from here and Set the 'webdriver.chrome.driver' property as below:

System.setProperty("webdriver.chrome.driver","C:\path\to\<<chromedriver_win_...>>\chromedriver.exe");

// Instantiate the ChromeDriver
WebDriver driver = new ChromeDriver();

// Visit the Selenium-WebDriver FAQ site
driver.get("http://seleniumwebdriverfaq.tumblr.com/");

// Print the title of the page - It should print "Selenium-WebDriver FAQ's"
System.out.println("Title of the page is: " + driver.getTitle());

//Close the browser window
driver.close();

//Quit the driver
driver.quit();
}
}

Tuesday, 7 February 2012

How can I instantiate InternetExplorerDriver?

The InternetExplorerDriver can be instantiated as below:


WebDriver driver = new InternetExplorerDriver(); // Instantiate the class - org.openqa.selenium.ie.InternetExplorerDriver

Sample code(Java Binding):


package tests;

import org.openqa.selenium.WebDriver;
import org.openqa.selenium.ie.InternetExplorerDriver;

public class InternetExplorerDriverSample {
public static void main(String[] args) {
// Instantiate the InternetExplorerDriver
WebDriver driver = new InternetExplorerDriver();

// Visit the Selenium-WebDriver FAQ site
driver.get("http://seleniumwebdriverfaq.tumblr.com/");

// Print the title of the page - It should print "Selenium-WebDriver FAQ's"
System.out.println("Title of the page is: " + driver.getTitle());

//Close the browser window
driver.close();

//Quit the driver
driver.quit();

}
}

Monday, 6 February 2012

How can I instantiate FirefoxDriver?

The FirefoxDriver can be instantiated as below:


WebDriver driver = new FirefoxDriver(); // Instantiate the class - org.openqa.selenium.firefox.FirefoxDriver

Sample code(Java Binding):


package tests;

import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;

public class FirefoxDriverSample {
public static void main(String[] args) {
// Instantiate the FirefoxDriver
WebDriver driver = new FirefoxDriver();

// Visit the Selenium-WebDriver FAQ site
driver.get("http://seleniumwebdriverfaq.tumblr.com/");

// Print the title of the page - It should print "Selenium-WebDriver FAQ's"
System.out.println("Title of the page is: " + driver.getTitle());

//Close the browser window
driver.close();

//Quit the driver
driver.quit();
}
}

How can I instantiate HTMLUnitDriver?

The HTMLUnitDriver can be instantiated as below:


WebDriver driver = new HtmlUnitDriver(); // Instantiate the class - org.openqa.selenium.htmlunit.HtmlUnitDriver

Sample code:


package tests;

import org.openqa.selenium.WebDriver;
import org.openqa.selenium.htmlunit.HtmlUnitDriver;

public class HTMLUnitDriverSample {
public static void main(String[] args) {
// Instantiate the HTMLUnitDriver
WebDriver driver = new HtmlUnitDriver();

// Visit the Selenium-WebDriver FAQ site
driver.get("http://seleniumwebdriverfaq.tumblr.com/");

// Print the title of the page - It should print"Selenium-WebDriver FAQ's"
System.out.println("Title of the page is: " + driver.getTitle());

}
}

What are the different implementations of WebDriver available?

Below are the WebDriver implementations available as off now:


1. HtmlUnitDriver
2. FirefoxDriver
3. InternetExplorerDriver
4. ChromeDriver
5. OperaDriver


6. AdroidDriver
7. IPhoneDriver

You can find out more information about each of these by following the links.

From where can I download set of Selenium tools?

Link below is where you can find the latest releases of all the Selenium components:


http://seleniumhq.org/download/