Wednesday 28 October 2015

ACCESSING WEB ELEMENTS

 

Selenium WebDriver is widely used tools in selenium tool set. To use Selenium WebDriver it is important to learn how it interacts with your application’s web elements. In this article, we will learn how to access your application’s web elements using Selenium WebDriver.

Below is the list of actions which is being used during your application’s test:

  • Accessing Text-Box.
  • Accessing Radio Buttons.
  • Accessing check Box.
  • Drop Down box Selection.
  • Synchronization.
  • Drag & Drop.
  • Keyboard Actions.
  • Mouse Actions.
  • Multi Selection.
  • Find all Links.

Accessing Text-Box

During your web application test the first thing you face is the text box for entering credentials for your application. In this section we will understand how to interact and access text box. We can put values into the text box using SendKey(). Similarly, we can retrieve the values using getattribute(“value”) command.

import org.openqa.selenium.WebDriver;

import org.openqa.selenium.By;

import org.openqa.selenium.firefox.FirefoxDriver;

import java.util.concurrent.TimeUnit;

public class Demo_Web_Elements {

public static void main(String[] args) throws InterruptedException {

// TODO Auto-generated method stub

WebDriver driver = new FirefoxDriver();

// Puts an Implicit wait, Will wait for 10 seconds

// before throwing exception

driver.manage().timeouts().implicitlyWait(10,TimeUnit.SECONDS);

// Launch website

driver.navigate().to("www.facebook.com");

// Maximize the browser

driver.manage().window().maximize();

// Enter value 10 in the first number of the percent Calculator

driver.findElement(By.xpath(".//*[@id='email']")).sendKeys("John@gmail.com");

Thread.sleep(5000);

// Get the text box from the application

String result = driver.findElement(By.xpath(".//*[@id='email']")).getAttribute("value");

// Print a Log In message to the screen

System.out.println(" The Result is " + result);

// Close the Browser

driver.close();

}

}

The output of this code is like this:

clip_image002

Accessing Radio Buttons

In this section, we will learn how to deal with radio buttons in your application. We just have to use click() to select and unselect radio buttons in your application.

We will understand accessing radio button using https://www.utexas.edu/learn/forms/radio.html. We can also check if a radio button is selected or enabled.

import org.openqa.selenium.WebDriver;

import org.openqa.selenium.By;

import org.openqa.selenium.firefox.FirefoxDriver;

import java.util.concurrent.TimeUnit;

public class Demo_Web_Elements {

public static void main(String[] args) throws InterruptedException {

// TODO Auto-generated method stub

WebDriver driver = new FirefoxDriver();

// Puts an Implicit wait, Will wait for 10 seconds

// before throwing exception

driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);

// Launch website

driver.navigate().to("https://www.utexas.edu/learn/forms/radio.html");

// Maximize the browser

driver.manage().window().maximize();

// Click on Radio Button

driver.findElement(By.xpath(".//*[@id='mr']")).click();

System.out.println("The Output of the IsSelected " +

driver.findElement(By.xpath(".//*[@id='mr']")).isSelected());

System.out.println("The Output of the IsEnabled " +

driver.findElement(By.xpath(".//*[@id='mr']")).isEnabled());

System.out.println("The Output of the IsDisplayed " +

driver.findElement(By.xpath(".//*[@id='mr']")).isDisplayed());

// Close the Browser.

driver.close();

}

}

The result of this code is:

clip_image004

Accessing check Box

In this section, we will learn how to run your test when you come across with check box during testing your application. We can select a check box using the click() and uncheck using the same click() method.

Let us understand how to interact with a dropdown box using //www.utexas.edu/learn/forms/checkboxes.html.

import org.openqa.selenium.WebDriver;

import org.openqa.selenium.By;

import org.openqa.selenium.firefox.FirefoxDriver;

import java.util.concurrent.TimeUnit;

public class Demo_Web_Elements {

public static void main(String[] args) throws InterruptedException {

// TODO Auto-generated method stub

WebDriver driver = new FirefoxDriver();

// Puts an Implicit wait, Will wait for 10 seconds

// before throwing exception

driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);

// Launch website

driver.navigate().to("https://www.utexas.edu/learn/forms/checkboxes.html");

// Maximize the browser

driver.manage().window().maximize();

// Click on check box

System.out.println("The Output of the IsSelected " +

driver.findElement(By.xpath(".//*[@id='graphics']")).isSelected());

driver.findElement(By.xpath(".//*[@id='graphics']")).click();

System.out.println("The Output of the IsEnabled " +

driver.findElement(By.xpath(".//*[@id='graphics']")).isEnabled());

System.out.println("The Output of the IsDisplayed " +

driver.findElement(By.xpath(".//*[@id='graphics']")).isDisplayed());

// Close the Browser.

driver.close();

}

}

Upon execution, the check box is unchecked after the click command (as it was checked by default) and the output of the commands are displayed in the console.

clip_image006

Drop down box Selection

In this section, we will understand how to interact with Dropdown Boxes. We can select an option using selectByVisibleText() or selectByIndex() or selectByValue() methods.

Let us understand how to interact with a dropdown box using

http://www.calculator.net/interest-calculator.html.

import org.openqa.selenium.WebDriver;

import org.openqa.selenium.By;

import org.openqa.selenium.firefox.FirefoxDriver;

import org.openqa.selenium.support.ui.Select;

import java.util.concurrent.TimeUnit;

public class Demo_Web_Elements {

public static void main(String[] args) throws InterruptedException {

// TODO Auto-generated method stub

WebDriver driver = new FirefoxDriver();

// Puts an Implicit wait, Will wait for 10 seconds

// before throwing exception

driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);

// Launch website

driver.navigate().to("http://www.calculator.net/interest-calculator.html");

// Maximize the browser

driver.manage().window().maximize();

// Selecting an item from Drop Down list Box

Select dropdown = new Select(driver.findElement(By.id("ccompound")));

dropdown.selectByVisibleText("continuously");

// you can also use dropdown.selectByIndex(1) to

// select second element as index starts with 0.

// You can also use dropdown.selectByValue("annually");

System.out.println("The Output of the IsSelected " +

driver.findElement(By.id("ccompound")).isSelected());

System.out.println("The Output of the IsEnabled " +

driver.findElement(By.id("ccompound")).isEnabled());

System.out.println("The Output of the IsDisplayed " +

driver.findElement(By.id("ccompound")).isDisplayed());

// Close the Browser.

driver.close();

}

}

Output

Upon execution, the dropdown is set with the specified value and the output of the commands are displayed in the console.

clip_image008

Synchronization

To synchronize between script execution and application, we need to wait for sometime after performing some actions. Let us look how to implement it.

Thread.Sleep

Thread.Sleep is a static wait and it is not a good way to use in scripts, as it is sleep without condition.

Thread.Sleep(1000); //Will wait for 1 second.

Explicit Waits

An 'explicit wait' waits for a certain condition to occur before proceeding further. It is mainly used when we want to click or act on an object once it is visible.

 
 

WebDriver driver = new FirefoxDriver();

driver.get("Enter an URL"S);

WebElement DynamicElement = (new WebDriverWait(driver,10)).until(ExpectedConditions.presenceOfElementLocated(By.id("DynamicElement")));

Implicit Wait

Implicit wait is used in cases where the WebDriver cannot locate an object immediately because of its unavailability. The WebDriver will wait for a specified implicit wait time and it will not try to find the element again during the specified time period.

Once the specified time limit is crossed, the WebDriver will try to search the element once again for one last time. Upon success, it proceeds with the execution; upon failure, it throws an exception.

It is a kind of global wait which means the wait is applicable for the entire driver. Hence, hardcoding this wait for longer time periods will hamper the execution time.

 
 

WebDriver driver = new FirefoxDriver();

driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);

driver.get("Enter an URL");

WebElement DynamicElement = driver.findElement(By.id("DynamicElement"));

Drag & Drop

As a tester, you might be in a situation to perform a 'Drag & drop' operation. We will perform a drag and drop operation by picking up a tree grid that is available for us on http://jqueryui.com/droppable/.

We will drop this small box into the big one by dragging it.

clip_image010

import org.openqa.selenium.WebDriver;

import org.openqa.selenium.By;

import org.openqa.selenium.WebElement;

import org.openqa.selenium.firefox.FirefoxDriver;

import org.openqa.selenium.interactions.Action;

import org.openqa.selenium.interactions.Actions;

import java.util.concurrent.TimeUnit;

public class Demo_Web_Elements {

public static void main(String[] args) throws InterruptedException {

// TODO Auto-generated method stub

WebDriver driver = new FirefoxDriver();

// Puts an Implicit wait, Will wait for 10 seconds

// before throwing exception

driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);

// Launch website

driver.navigate().to("http://jqueryui.com/droppable/");

// Maximize the browser

driver.manage().window().maximize();

WebElement From =

driver.findElement(By.xpath(".//*[@id='draggable']"));

WebElement To =

driver.findElement(By.xpath(".//*[@id='droppable']"));

Actions builder = new Actions(driver);

Action dragAndDrop = builder.clickAndHold(From).moveToElement(To).release(To).build();

dragAndDrop.perform();

// Close the Browser.

driver.close();

}

}

Output

clip_image012

Keyboard Actions

For performing keyboard actions following methods are used:

· sendKeys() - Sends keys to the keyboard representation in the browser. Keys are recognized both as part of sequences of characters, or individually.

· pressKey() – Used to press keys on the keyboard that is NOT text. The keys such as function keys "F1", "F2", "Tab", "Control", etc. If key is a sequence of characters, different driver implementations may choose to throw an exception or to read only the first character in the sequence.

· releaseKey() - Release a key on the keyboard after executing the keypress event. It usually holds good for non-text characters.

Syntax

 
 

void sendKeys(java.lang.CharSequence keysToSend);

void pressKey(java.lang.CharSequence keyToPress);

void releaseKey(java.lang.CharSequence keyToRelease);

Mouse Actions

For performing mouse actions following methods are used:

· Click() –To performs a Click. We can also perform a click based on coordinates.

· contextClick() – To Performs a context click/right-click on an element or based on the coordinates.

· doubleClick() – To performs a double-click on the webelement or based on the coordinates. If left empty, it performs double-click on the current location.

· mouseDown() – To performs a mouse-down action on an element or based on coordinates.

· mouseMove()- To performs a mouse-move action on an element or based on coordinates.

· mouseUp() – To releases the mouse usually followed by mouse-down and acts based on coordinates.

Syntax

 
 

void doubleClick(WebElement onElement);

void mouseDown(WebElement onElement);

void mouseUp(WebElement onElement);

void mouseMove(WebElement toElement);

void mouseMove(WebElement toElement, long xOffset, long yOffset);

Find All Links

Testers might be in a situation to find all the links on a website. We can easily do so by finding all elements with the Tag Name "a", as we know that for any link reference in HTML, we need to use "a" (anchor) tag.

For the demonstration we will grab all the links exists on the login page of www.facebook.com.

import java.util.concurrent.TimeUnit;

import org.openqa.selenium.WebDriver;

import org.openqa.selenium.By;

import org.openqa.selenium.WebElement;

import org.openqa.selenium.firefox.FirefoxDriver;

public class Demo_Web_Elements {

public static void main(String[] args) throws InterruptedException {

// TODO Auto-generated method stub

WebDriver driver = new FirefoxDriver();

driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);

// Launch website

driver.navigate().to("www.facebook.com");

// Maximize the browser

driver.manage().window().maximize();

java.util.List<WebElement> links =driver.findElements(By.tagName("a"));

System.out.println("Number of Links in the Page is " +links.size());

for (int i = 1; i<=links.size(); i=i+1)

{

System.out.println("Name of Link# " + i + "-" + links.get(i).getText());

}

}

}

Output

clip_image014

Generation Xpaths

XPath is a syntax for defining parts of an XML document. XPath uses path expressions to navigate in XML documents. XPath contains a library of standard functions. Now, there could be a situation when we face problem to grab the Xpaths. In that case we can generate xpath by our own by analysing the XML code.

Below table will help you out to make your own xpath from XML script.

Expression

Description

nodename

To select all nodes with the name “nodename”.

/

To select from the root node.

//

Selects node in the document from the current node that matches the selection no matter where they are.

.

Selects the current node.

..

Selects parent of the current node.

@

Select the attributes.

Example

Let’s create a xpath for firstname field of facebook login form:

clip_image016

Step 1: Select first name

//input[@id='firstname] OR //input[@name=firstname]

In this case no need of xpath locator because we can use By.id, By.name,By.cssSelector.

By.id("firstname") | By.name("firstname") | By.cssSelector("[id=firstname]")

Step 2: Selecting first name input using First Name label

//label[text()='First Name:']/parent::td/following-sibling::td/div/input

OR

//label[text()='First Name:']/../../td/div/input

What’s next?

In next article we will learn different test design techniques that simplifies your code and also make it more understandable and dynamic.

No comments:

Post a Comment