Selenium 2.0 WebDriver – Some useful APIs

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.

Comments 29

  • 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 🙂

  • 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

  • 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

  • Afghanistan
    Albania
    India
    China

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

  • sel.selectByValue(“India”);

  • Hi Seetaram,

    In

  • 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.

    • 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…

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

    thanks and regards.,
    Babu.m

  • 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

    • 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,

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

  • 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

  • Document is Good.. Thanks

  • 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

  • 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

  • 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?

    • 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

  • 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.

    • 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

  • 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?

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

  • Hi

    I am trying to do a button click where i am using webdriver with java. The following is the html code for the button.


    Create New eWALLET

    I want to test this on firefox , I tried doing as below but none of them worked out for me Please help me resolve the same-
    1) driver.findElement(By.partialLinkText(“Create New eWALLET”)).click();
    driver.findElement(By.partialLinkText(“Create New eWALLET”)).clear();

    2) driver.findElement(By.xpath(“//a[@href=’wallet.html’]”)).click();

    3) driver.findElements(By.xpath(“//a[@class=’pure-button pure-button-primary’]/span/span[contains(text(), ‘Create New eWALLET’)]”))

    4) driver.findElement(By.cssSelector(“#pure-button”)).click();
    driver.findElement(By.cssSelector(“#pure-button”)).clear();

  • Hi Seetaram,

    i am not getting the checkbox name in spicejet site.
    There are 4 checkboxes present in home page.
    could you please tell me why it is not working.

    System.setProperty(“webdriver.chrome.driver”,”D://chromedriver.exe”);
    WebDriver w=new ChromeDriver();
    w.get(“http://spicejet.com”);
    //String s=w.findElement(By.id(“ctl00_mainContent_chk_StudentDiscount”)).getAttribute(“type”);
    Listwe=w.findElements(By.cssSelector(“input[type=’checkbox’]”));
    System.out.println(we.get(0).getAttribute(“label”));
    System.out.println(we.get(1).getAttribute(“label”));
    System.out.println(we.get(2).getAttribute(“label”));
    System.out.println(we.get(3).getAttribute(“label”));

    it is returning null
    result:

    Starting ChromeDriver (v2.9.248315) on port 15752
    null
    null
    null
    null

  • I dont know this forum/thread is still active or not .. however the piece of code in main article

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

    has not worked for me.
    neither the variants

    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.”);

    worked for me.
    I am using ‘Eclipse’ and FireFox webdriver, and get syntax/token errors for all the above mentioned codes (even after adding the import files mentioned).
    Can someone suggest me the way out.

    Regards,
    Rizwan

  • […] provided by the Selenium 2 Web driver.  Some of the useful APIs were discussed in detail in “Useful APIs of WebDriver”.  Example of automating a web page with these APIs explains the Test Automation with WebDriver […]

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.