Selenium 2.0 WebDriver – Some useful APIs

by seetaram on July 23, 2011

To start with WebDriver we need to learn about some of the useful APIs that are provided for automating user actions on an application.

Let us list some of the actions that we need to automate while automating a test case:

  1. Click a link, button
  2. Type value in an Edit box
  3. Select a value from the dropdown
  4. “Check / Uncheck “ a checkbox
  5. Select a radio button

This is exactly what I am going to discuss in this post.

Click a link / button:

To click on an object through webdriver first we need to find out which locator we are going to use.  Is it ID, name, xpath, or css? For this purpose we can utilize firebug / xpath checker to find out is there any id / name exists for the object we are going to perform action upon.  Then write the code as below:

driver.findElement(By.xpath("//a[@href='CustomerInfo.htm']")).click();

In the above line of code “driver” could be FirefoxDriver, InternetExplorerDriver, ChromeDriver, HtmlUnitDriver, etc.  On one of these browsers we are going to find an element and then click as per the code.

findElement is an API provided by the webdriver which requires argument “By.xpath”.  The “xpath” can be replaced by one of the below methods if we need to identify the element with any other attributes such as css, name, classname, etc:

  1. className
  2. cssSelector
  3. linkText
  4. name
  5. partialLinkText
  6. tagName
  7. xpath
  8. id

To understand the above methods one needs the basic understanding of the HTML.  Id, name, input, type, a, etc are the HTML tags / attributes.  Using these HTML tags and attributes “xpath” can be constructed and this I have already explained in one of my earlier posts (How to write xpath)

Type value in an Editbox

Have a look at the below line of code.

driver.findElement(By.name("FirstName")).sendKeys("Google");

Here the webdriver finds the object first with findElement API and then keys in the value with sendKeys method.

Select a value from the dropdown

To select a value from a dropdown, follow the below steps:

  1. Declare a List and assign all the values of dropdown using findElements method
  2. Use a for loop to go through the elements one by one
  3. Using an IF condition match the required option
  4. Click the required option (.setSelected is deprecated)

Use the below code and put that into a function which does the job.

	public static void selectValue(String valToBeSelected){
        List <WebElement> options = driver.findElements(By.tagName("option"));
		for (WebElement option : options) {
			if (valToBeSelected.equalsIgnoreCase(option.getText())){
				option.click();
			}
		    } 
	}

call the static method wherever necessary – selectValue(“Texas”) will select the value Texas from the dropdown country.

“Check / Uncheck “ a checkbox

To “Check / Uncheck” a checkbox, the object needs to be identified using findElement method and then just click.  To find out whether the checkbox is checked or not utilize the method – element.isSelected()

        WebElement kancheck = driver.findElement(By.name("kannada"));
        kancheck.click();
        System.out.println(kancheck.isSelected());

Above code snippet will first click the checkbox named kannada and then verifies whether it is clicked or not.

Select a radio button

Follow the same steps which are used in Checkbox to select a radio button and then verify the status using isSelected() method.

        WebElement gender = driver.findElement(By.xpath("//input[@name='male']"));
        gender.click();
        System.out.println(gender.isSelected());

Above are the basic actions needed for Test Automation.  I will try to explain this with an example in the next post.

{ 25 comments… read them below or add one }

Rahul November 8, 2011 at 2:02 pm

Hi Seetaram,
I want to select country as “India” from drop down list, I have written code as given below.
But I’m getting compilation error while doing so. Can you please let me know the reason.
Also, don’t we have direct api to select value from drop down list in Webdriver?

public void selectValue(String valToBeSelected){
WebElement we = driver.findElement(By.name(“country”));
//error in the below line as “the type list is not generic, it can not be parameterised with args”
List options = we.findElements(By.tagName(“option”));
for (WebElement option : options)
{
if (valToBeSelected.equalsIgnoreCase(option.getText()))
{
option.click();
break;
}
}
}

Thanks in adv
Rahul :)

Reply

seetaram November 9, 2011 at 3:38 am

Dear Rahul,

The reason might be:
1. WebElement is not imported
2. List is not imported

Solution:
import java.util.List;
import org.openqa.selenium.WebElement;

Use the below code:

Select select = new Select(driver.findElement(By.id(“salutation”)));
select.selectByValue(ValToBeSelected);

We can modify your code as below:
Select select = new Select(driver.findElement(By.name(“country”)));
select.selectByValue(“Mr.”);

For the above code to work, you need to add the import statement as below:
import org.openqa.selenium.support.ui.Select;

– Seetaram

Reply

Rahul November 9, 2011 at 10:00 am

Thank you very much Seetaram, I have tried on both the ways given above.. Working fine now..
I have one quick query ::

Suppose this is the source ::

Afghanistan
Albania
India
China

Here,

Select sel = new Select(driver.findElement(By.name(“country”)));
sel.selectByValue(“”);
–> It selected China, As the value given is empty which matches with the value of China

Select sel = new Select(driver.findElement(By.name(“country”)));
sel.selectByIndex(3);
–> It selected China , As index starts from 0 and China is the 3rd element

If I want to select by option’s text i.e by using “India”, rather than using value as 3 or index as 2, How can I do that?

–Rahul

Reply

Rahul November 9, 2011 at 10:02 am

Afghanistan
Albania
India
China

Reply

Rahul November 9, 2011 at 10:04 am

select name=”country”
option value=”1″>Afghanistan /option
option value=”2″>Albania /option
option value=”3″>India /option
option value=”*”>China /option
/select

Reply

seetaram November 9, 2011 at 12:04 pm

sel.selectByValue(“India”);

Reply

Mahesh January 4, 2012 at 5:45 pm

Hi Seetaram,

In

Reply

Mahesh January 4, 2012 at 5:50 pm

I want to select “Unread” value from drop down in gmail home screen.
In testCreateAccount Class, i write below code:

selectValue(driver,”Unread”);

and calling by

public static void selectValue(WebDriver driver, String valToBeSelected){
List options = driver.findElements(By.id(“:pj”));
for (WebElement id : options) {
if (valToBeSelected.equalsIgnoreCase(id.getText())){
id.click();
}
}

But its not selecting “Unread” from drop down. Please suggest.

Reply

seetaram January 5, 2012 at 9:04 am

Above method does not work for this… check the HTML source code associated with Gmail home and then you need to tweak this java method according to your needs…

Reply

babu February 18, 2012 at 9:40 am

hi ,seetaram.,
Can u give some examples of webdriver apis like find element

thanks and regards.,
Babu.m

Reply

shmon March 15, 2012 at 2:36 am

Hi Seetaram,

I’m trying to select a checkbox but webdriver is not able to find the element on page, it is selecting radio boxes just fine;

WebElement element = driver.findElement(By.id(“123″));

if(element.isDisplayed()) {
element.click();
System.out.println(element.isSelected());
}

But it gives error that Unable to locate element. Any idea?

Thanks

Reply

Shady September 6, 2013 at 5:53 am

Hi Shmon,

may be the webpage u r working on contains a frame, u must check it out and use the frameswitch() function.
hope ur query will be solved.

Thanks,

Reply

sreekumar April 5, 2012 at 11:13 am

Please give example / usage of isSelected() for a dropdownlist. My requirement is to verify selected item from the dropdown list.

Reply

ramu m November 16, 2012 at 12:43 pm

how to get some(10)locators using for-loop in selenium web driver
in one web page using xpath,id,name….

please suggest me sir

thanking you sir in advance

Reply

Lakshmi May 17, 2013 at 9:41 am

Document is Good.. Thanks

Reply

Mahesh July 4, 2013 at 11:51 am

Hi Sitaram
I am new in automation testing
i have write code of login page after that i am stuck in how to select items from drop down
please help me

Reply

Devin August 28, 2013 at 3:24 pm

Hi, Sitaram

With selenium webDriver, How simulate keystrokes Caps Lock key?

I known there is a action class is possible, but Ijust understand Common keys, such as enter, backspace, tab.
For A common key, the direct use sendkeys (theKeys) can be, such as pressing the enter key:
action.sendKeys (Keys.ENTER). perform ();

Four modifier keys (Modifier Keys) Caps Lock, Control, Option, Command is not very clear how to use?

Thanks
Devin

E-mail:annclass@163.com

Reply

seetaram August 30, 2013 at 10:54 am

Hi Devin,

Use Java robot framework for keystroke simulation. Refer http://stackoverflow.com/questions/2596641/simulate-backspace-key-with-java-awt-robot/2596700#2596700

Cheers!!
Seetaram

Reply

satinder September 5, 2013 at 12:01 pm

hello sir i m new to selenium , and trying to learn it. got some success but now i m stuck at one point. actually i m trying to test a facebook game using selenium which is developed in php. so my question is that can we test a facebook game using selenium?

Reply

seetaram September 5, 2013 at 1:44 pm

If the Selenium is identifying the objects on the Game page, then YES. Try to record a scenario on the game page. If the selenium is identifying the objects on the game page then go ahead.

Cheers!!
Seetaram

Reply

Madhu September 24, 2013 at 9:20 am

Hi Seetharam,

I am new to Selenium, and trying to learn it. got some success but now i m stuck at one point. I am trying to click on Radio button on Mecury tour website, but i am getting error messageException in thread “main” org.openqa.selenium.NoSuchElementException: Unable to find element with id == document.findflight.tripType[1] (WARNING: The server did not provide any stacktrace information)
Command duration or timeout: 10.21 seconds
For documentation on this error, please visit: http://seleniumhq.org/exceptions/no_such_element.html
Build info: version: ’2.35.0′, revision: ’8df0c6b’, time: ’2013-08-12 15:43:19′
System info: os.name: ‘Windows 7′, os.arch: ‘x86′, os.version: ’6.1′, java.version: ’1.6.0_30′
Session ID: 343c0c61-7bf4-4b63-9944-dd73eac5cc16
Driver info: org.openqa.selenium.ie.InternetExplorerDriver

Please help.

Reply

seetaram September 25, 2013 at 6:05 am

First and foremost thing in automation is to learn how an automation tool identifies the objects on the Application Under Test. I strongly suggest you to first understand the object identification by Selenium and then start coding.

Here in your exception stack .. it clearly says that Selenium is unable to find the Element so you have to debug and find why it is not able to identify the element.

Cheers!!
Seetaram

Reply

Biswajit February 17, 2014 at 2:16 pm

Hi Seetaram,

Please advise where I am going wrong in my understanding.

If I write something like this

WebElement we1 = driver.FindElement(By.TagName(“”);
WebElement we2 = we1.FindElement(By.XPath(“/a[@target='_xyz']“);
The element we2 should now point to the anchor tag with the target as _xyz.

Should I write it as /a or //a?

Reply

seetaram February 19, 2014 at 8:57 am

“/” is absolute whereas “//” is relative use these according to your needs

Reply

Surender February 19, 2014 at 6:08 am

Hi Seetaram,
I want all url in list those have “news ” keyword in url.

My code is

package test;

import java.util.List;
import java.util.concurrent.TimeUnit;

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

public class link {

public static void main(String[] args) {

WebDriver driver=new FirefoxDriver();

driver.manage().window().maximize();
driver.get(“https://www.google.co.in”);

driver.findElement(By.className(“gbqfif”)).sendKeys(“news”);
driver.findElement(By.className(“gbqfb”)).click();

List alllinks = driver.findElements(By.tagName(“a”));
for (int i =0; i<= alllinks.size()-1; i++){
String oflinks = alllinks.get(i).getText();

System.out.println(alllinks.get(i).getText());

Reply

Leave a Comment

Previous post:

Next post:

Do you want to get updates on the recent articles written? Please subscribe to RSS feed or Email