Software Testing Learning Hub

Selenium Lesson 12 – Handling webelements

Lesson 12 Handling WebElements

In this lesson we will look at how we will selenium webdriver perform operations on different webelements such as links, buttons, textbox, dropdowns etc. often we do not get consolidated list of operations over webelements, This post will help you in it.

we are going to take a look at following webelements.

  • Link
  • Button
  • TextBox/Input
  • ComboBox
  • TextArea
  • Radiobutton
  • Checkbox
  • iFrame

 

Link : There two operations can be performed on Links

  • Click on Link
  • Get Linktext

following code will help you perform these two operations.

Click on Link :  we will use normal click operation by sending the link xpath. you can use any object identification.

driver.FindElement(By.XPath("Link Xpath")).Click();

Get Link Text :  we will use list to get the link text

public class Seleniumwebdriver
{
  public static void main(String[] args)
  {
        WebDriver driver =new FirefoxDriver(); // initiate selenium webdriver
        driver.get("http://www.google.com"); // got to google.com
        List<WebElement> elements = driver.findElements(By.tagName("a")); // store elements, give link xpath
        for(WebElement element : elements)  // print elements
            {
              System.out.println(element.getText());
            }
  }
}

 

Button: 

By ID:

 WebDriver driver =new FirefoxDriver(); // initiate selenium webdriver
 driver.findElement(webdriver.By.id('gbqfb')).click();

By Xpath:

 WebDriver driver =new FirefoxDriver(); // initiate selenium webdriver
 driver.FindElement(By.XPath("Link Xpath")).Click();

Using  JavaScript :

JavascriptExecutor jse = (JavascriptExecutor)driver;
jse.executeScript("document.getElementById('<buttonID>').click();");

Get button Caption

WebDriver driver =new FirefoxDriver(); // initiate selenium webdriver
driver.findElement(By.XPath("//input[@name='submit']")).getAttribute("value");

 

TextBox/Input / TextArea::

Enter Value :

 WebDriver driver =new FirefoxDriver(); // initiate selenium webdriver
 driver.FindElement(By.XPath("Link Xpath")).Sendkeys("1000");

Clear value in Textbox:

 WebDriver driver =new FirefoxDriver(); // initiate selenium webdriver
 driver.FindElement(By.XPath("Link Xpath")).clear();

ID, name will be used in same manner.

 

DropDown/ Pull down:

WebElement dropDownListBox = driver.findElement(By.id("<DropdownID>"));
Select clickThis = new Select(dropDownListBox);
clickThis.selectByVisibleText("<Item in dropdownlist>");

 

Radio button /Checkbox:

Select Radio button:

 driver.FindElement(By.XPath("Link Xpath")).Click();

Find if the radio button is selected or not:

boolean isselected = driver.findElement(By.xpath("< xpath of option which you find whether is selected or not ")).isSelected()

 

Iframe:

Switch to iframe:

driver.switchTo().frame(driver.findElement(By.id("frameId")));//do your stuff
driver.switchTo().defaultContent();