What are Locators?
What are Locators?
Locator is a command to identify the GUI elements for operation by Selenium IDE. The GUI elements can be text box, buttons or checkboxes. Identification of correct GUI elements is a prerequisite to creating an automation script. In other words Locators provide a way to access the HTML elements from a web page. They are the basic building blocks of a web page. A web developer must use a proper and consistent locator scheme for a website. Also, a test engineer must choose the correct locator strategy to automate the online workflows. Selenium names different types of locators to find the elements on a web page. Webdriver references the Web elements by using the findElement(By.<locator()>) method. The findElement method uses a locator/query object known as
<“By”>. There are various kinds of “By” strategies which can utilize depending on the requirements as below:
a) By ID.
Syntax
driver.findElement(By.id(<element ID>))
According to this strategy, the By method will return the first element matching the id attribute value. If it doesn’t find any matching element then, it’ll raise a NoSuchElementException. Using element Id is the most preferred way to locate an element, as usually Ids have unique values.
Example:
<input id="TechBeamers">
// Java example code to find the input element by id.
WebElement user = driver.findElement(By.id("TechBeamers"));
b) By Name.
Syntax
driver.findElement(By.name(<element-name>))
By.Name() is another useful way to locate an element. This strategy states that the <By.Name()> method will return the first element matching the name attribute. If it’s not able to locate it then, it’ll throw a NoSuchElementException.
Example:
<input name="TechBeamers">
// Java example code to find the input element by name. WebElement user = driver.findElement(By.name("TechBeamers"));
c) By Class Name.
Syntax:
driver.findElement(By.className(<element-class>))
This method gives the element which matches the values specified in the “class” attribute. If the element has more than one class, then this method will match against each one of them.
Example:
<input class="TechBeamers">
// Java example code to find the input element by className. WebElement user = driver.findElement(By.className("TechBeamers"));
d) By TagName.
Syntax:
driver.findElement(By.tagName(<html tag name>))
This method is used to find the elements matching the specified tag name. This method can be call to extract the content within a tag or wish to perform any action on the tag element.
Example:
<form action="viewuser.asp" method="get"
id="userform"> Name: <input type="text"
name="name"><br>
Age: <input type="text" name="age"><br>
</form>
<button type="submit" form="userform"
value="Submit">Submit</button> WebElement form =
driver.findElement(By.tagName("button"));
// Any action can be perform on the form button. form.submit();
Syntax:
driver.findElement(By.cssSelector(<css-selector>))
With this method, a CSS selector can be used to locate the element. The CSS is cascading style sheet; it sets the styles for a web page and its elements.
Example:
<input class="email" id="email"
type="text" placeholder="[email protected]">
<input class="btn btn-small" type="submit" value="Subscribe to our blog">
// Java code example for using cssSelector.
WebElement emailText =
driver.findElement(By.cssSelector("input#email"));
//Or
WebElement emailText =
driver.findElement(By.cssSelector("input.email"));
WebElement subscribe =
driver.findElement(By.cssSelector("input[type='submit'][value='Subsc ribe to our blog']"));
f) By XPath.
Syntax:
driver.findElement(By.xpath(<xpath>))
This method is use to locate an element using the XPath query. XPath is a way to traverse through the of document object model, gives you the ability to select specific elements, attributes, or a section of an XML document.
Example:
// Java code example for XPath.
// Absolute path. WebElement item =
driver.findElement(By.xpath("html/head/body/table/tr/td"));
// Relative path.
WebElement item = driver.findElement(By.xpath("https://input"));
// Finding elements using indexes.
WebElement item = driver.findElement(By.xpath("https://input[5]"));
// Finding elements using attributes values.
WebElement item = driver.findElement(By.xpath("img[@alt='banner']"));
// XPath starts-with() example.
// => input[starts-with(@id,'User')]
// XPath ends-with() example.
// => input[ends-with(@id,'_name')]
// XPath contains() example.
// => input[contains(@id,'email')]
HTML Basics
HTML (Hypertext?Markup Language) is a markup language that defines the structure of content. It is the language in which most websites are written. It is used to create pages and make them functional. The code used to make them visually appealing is known as CSS.
HTML consists of a series of elements, which can be used to enclose, or wrap, different parts of the content to make it appear a certain way, or act a certain way. The enclosing tags can make a word or image hyperlink to somewhere else, can italicize words, and can make font bigger or smaller, and so on.
HTML Language Tags and Attributes
A?Markup Language?can be define as a way that computers speak to each other to control how text is processed and presented. To do this HTML uses two things:?tags and attributes.
HTML Tags
Tags are used to mark up the start of an HTML element and they are usually enclosed in angle brackets. HTML elements are written with a start tag, with an end tag, with the content in between:
<tagname> content </tagname>. The HTML element is everything from the start tag to the end tag:
<p> My first HTML paragraph. </p>
HTML elements can be nested (elements can contain elements). All HTML documents consist of nested HTML elements. An example of a tag is: <h1>. Most tags must be opened <h1> and closed
</h1> in order to
function HTML Attributes
Attributes contain additional pieces of information. Attributes take the form of an opening tag and additional info is placed inside. An example of an attribute is:
<img src="logo.gif" alt="An image of the company’s logo.">
In this instance, the image source (src) and the alt text (alt) are attributes of the <img> tag. The other attributes are:
Difference Between Absolute and Complete Xpath
XPath is a technique for walking through the DOM structure of the web page. XPath locators are robust and reliable. It is one method which guarantees to locate any element on the page using the XPath expression. The XPaths can be classified in the following two groups.
a) Absolute XPath.
It starts from the root element within the web page or part of the page and goes to identify the target element.
Example:
HTML/head/body/table/tr/td
To use locators like the XPath is easy as you give the direct element path. But the XPath would break when the element structure changes.
b) Complete XPath or Relative XPath
The complete XPath are easy to manage as they are short and concise. It is also better than the previous XPath style as it may survive the changes in the Page HTML to a certain degree. Though, building a complete XPath is time-consuming and quite difficult as you need to check all the nodes to form the path.
Example:
//table/tr/td
Finding Your First Element
Everything that is present on the web page is an element. An element is equivalent to a tag in HTML. One of the most important skills of a test automation engineer working with Selenium WebDriver is to be able to use appropriate methods to locate elements on a page. WebDriver users the SearchContext interface to locate elements on any page. The SearchContext interface has two methods:
There are multiple ways to uniquely identify a web element within the web page such as ID, Name, Class Name, Link Text, Partial Link Text, Tag Name and XPATH. Find Element command is used to uniquely identify a (one) web element within the web page. Whereas, Find Elements command is used to uniquely identify the list of web elements within the web page.
FindElement
Find Element command takes in the By object as the parameter and returns an object of type WebElement. By object in turn can be used with various locator strategies such as ID, Name, Class Name, XPATH etc. The syntax of FindElement command in Selenium web driver.
WebElement elementName =
driver.findElement(By.LocatorStrategy("LocatorValue"));
A Locator Value is the unique value using which a web element can be identified. Locator Strategy can by any of the following values.
Example:
WebElement loginLink = driver.findElement(By.linkText("Login"));
FindElements
Find Elements command takes in By object as the parameter and returns a list of web elements. It returns an empty list if there are no elements found using the given locator strategy and locator value. The syntax of find elements command.
List<WebElement> elementName = driver.findElements(By.LocatorStrategy("LocatorValue"));
Example:
List<WebElement> listOfElements = driver.findElements(By.xpath("https://div"));
Example:
package com.sample.stepdefinitions;
import java.util.List;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
public class NameDemo {
public static void main(String[] args) {
System.setProperty("webdriver.chrome.driver", "X://chromedriver.exe");
WebDriver driver = new ChromeDriver(); driver.get("https://www.ducatindia.com/test/ajax.html");
List
< WebElement >
elements = driver.findElements(By.name("name")); System.out.println("Number of elements:" + elements.size()); for (int i = 0; i < elements.size(); i++) {
System.out.println("Radio button text:" +
elements.get(i).getAttribute("value"));
} }
WebElement Commands
WebElement is the smallest possible HTML entity that helps to form a fully functional web page. In other words a WebElement represents an HTML element. In Webdriver terminology, it is a Java class which represents an object that holds the reference to an HTML element. For example, In the below HTML code, the whole div including opening and closing tag is forming an HTML element.
<div id=’employee’>…</div>
Every method of the WebDriver either returns something or return void(means return nothing). The same way findElement command of WebDriver returns WebElement. In order to get the WebElement object the below statement is used
WebElement element = driver.findElement(By.id(“UserName“));
WebElement can be of any type, such as a Text, Link, Radio Button, Drop Down, WebTable or any HTML element. Above command will list all the actions against the any element irrespective of whether the action is valid on the WebElement or not. The Selenium Webdriver action commands associated with the web elements are:
clear() :?This method will clear the value of any text type element. It doesn’t allow any parameter and its return type is also void. This method doesn’t impact any HTML element other than the field of text type.
Syntax:
element.clear();
Example:
WebElement user = driver.findElement(By.id("User")); user.clear();
sendKeys(CharSequence… keysToSend ):?This method types in the values passed in the argument into the associated web element object. It allows a CharSequence as a parameter, and its return type is void. This method supports elements like INPUT and TEXTAREA elements.
Syntax:
element.sendKeys(“enter text”);
Example:
WebElement user = driver.findElement(By.id("User"));
user.sendKeys("TechBeamers");
click( ):?This method performs the click action at the web element. It doesn’t accept any parameter, and its return type is void. It is one of the most common methods which interacts with the web elements like links, checkboxes, buttons, etc.
Syntax:
element.click();
Example:
WebElement link = driver.findElement(By.linkText("TechBeamers")); link.click();
boolean isDisplayed( ):?This method checks the visibility of a web element. It doesn’t allow any parameters but its return type is a boolean value. This method will return true if the element is present and visible on the page. It’ll throw a NoSuchElementFound exception if the element is not available. If it is available but kept as hidden, then the method will return false.
Syntax:
element.isDisplayed();
Example:
WebElement user = driver.findElement(By.id("User"));
boolean is_displayed = user.isDisplayed();
boolean isEnabled( ):?This method return true/false depending on the state of the element (Enabled or not). This method will usually return true for all items except those which are intentionally disabled.
Syntax:
element.isEnabled();
Example:
WebElement user = driver.findElement(By.id("User"));
boolean is_enabled = user.isEnabled();
boolean isSelected( ):?This method tests if a element is active or selected. It doesn’t allow any parameter, but it does return a boolean status. This method is only applicable for input elements like Checkboxes, Radio Button, and Select Options. It’ll return true when it finds the element is currently selected or checked.
Syntax:
element.isSelected();
Example:
WebElement lang = driver.findElement(By.id("Language"));
boolean is_selected = lang.isSelected();
void submit( ):?This method initiates the submission of an HTML form. It doesn’t allow any parameter and its return type is void. If the method is leading the current page to change, then it would wait until the new page gets loaded.
Syntax:
element.submit();
Example:
webElement submit_form = driver.findElement(By.id("Submit"));
submit_form.submit();
String getText( ):?This method will give you the innerText value of the element. You must note that the innerText property is CSS aware and the getText() method would return a blank if the text is hidden. This method provides the innerText of the associated element. The output includes the sub- elements and leaves any leading or trailing whitespace aside.
Syntax:
element.getText();
Example:
WebElement link = driver.findElement(By.xpath("MyLink"));
String strlink = link.getText();
String getTagName( ):?This method provides the tag name of the associated element. It doesn’t allow to pass any parameter and returns a String object. It’ll return the tag name i.e. “input“ of the element. e.g. <input name=”Password”/>.
Syntax:
element.getTagName();
Example:
WebElement pass = driver.findElement(By.id("Password"));
String strTag = pass.getTagName();
String getCssValue( String propertyName):?This method provides the value of the CSS property belonging to the given element. This method may return an unpredictable value in a cross-browser setup. Like, you would have set the “background-color” property to “green” but the method could return “#008000” as its value.
Syntax:
element.getCssValue(“font-size”);
Example:
webElement name = driver.findElement(By.id("Name"));
String strAlign = name.getCssValue("text-align");
getSize( ) –?This method returns the height and width of the given element. It doesn’t allow to pass any parameter, but its return type is the Dimension object. This methods provides the size of the element on the web page.
Syntax:
element.getSize();
Example:
WebElement user = driver.findElement(By.id("User"));
Dimension dim = user.getSize();
System.out.println(“Height # ” + dim.height + ”Width # "+ dim.width);
getLocation( ):?This method locate the location of the element on the page. It doesn’t allow to pass any parameter, but its return type is the Point object. This method provides the Point class object.
Syntax:
element.getLocation();
Example:
WebElement name = driver.findElement(By.id("Name"));
Point point = name.getLocation();
String strLine = System.getProperty("line.separator");
System.out.println("X cordinate# " + point.x + strLine + "Y cordinate# " + point.y);
Summary