WebElement in Selenium

Anything present on the webpage such as textbox, text, button, link, table, radio button, checkbox etc, are called as webelement.

web elements in selenium-webdriver

Before performing any action on webelement (typing, clicking, selecting etc ), selenium has to uniquely identify those elements.

In order to use this, it uses few of the characteristics(8 types) are given by the developer while developing the webpage using html.

How to find WebElement ?

In order to interact with UI objects with Selenium WebDriver we need to be able to identify webpage elements fast and in an accurate way(sometimes uniquely). We don’t want to refactor these locators very often so we must choose the right locators from the start.

There are some browser tools that you can use in order to identify web elements in the DOM easier.

1. Firebug for Firefox
2. Google Developer Tools for Chrome
3. Web Inspector for Safari

We will explore the above tools in following tutorials.

Locators in Selenium

Selenium uses locators to find and match the elements of the page that it needs to interact with. There are 8 locators are present in Selenium:

  • Id
  • Name
  • ClassName
  • TagName
  • LinkText
  • Partial Link text
  • CSS
  • Xpath

Below image the highlighted the locators present in selenium locators in selenium-webdriver

Apart from these 8 locators we have another 18 more inbuilt locators, Selenium api provides power to the user to create custom locators in selenium.

Read QR Code using Selenium

Priority of Locators in Selenium

Automation developer should the locator in below order, so the failures will get reduced, if id has more than one match then user should try with Name so on..

  • Id
  • Name
  • ClassName
  • CSS
  • Xpath

How to open developer tools to find elements

By doing following operation in respective browser we can open the developer tools

  • IE: Developers Tool (Tools –> Developers Tools/ F12)
  • Chrome: Build in Page analyzing feature (right click –> Inspect Element / F12)
  • Firefox: Firebug add on. Right click on any element and select Inspect Element or F12

Sample HTML for Locators Example




									<html>
										<body>
											<div id="pancakes">
												<a href="https://chercher.tech" >Selenium Webdriver</a>
												<button id="firstButton" type="button">Blueberry</button>
												<button type="button" name="Ban" class="Banana">Banana</button>
												<button type="button" name="cake" value="Strawberry">Strawberry</button>
											</div>
										</body>
									</html>


								

attributes in selenium-webdriver

Id

The Id locator looks for an element in the page having an id attribute


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

										public class ElementLocators {
											public static void main (String [] args){
												WebDriver driver = new FirefoxDriver();
												driver.get("https://chercher.tech/locator-example")
												driver.findElement(By.id("firstButton")).click();
											}
										}


									

Name

The name locator looks for an element in the page having an name attribute


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

											public class Locators {
												public static void main (String [] args){
													WebDriver driver = new FirefoxDriver();
													driver.get("https://chercher.tech/locator-example");
													// Below line matches with banana button
													driver.findElement(By.name("Ban")).click();
												}
											}
										

Class Name

The Class name locator looks for an element in the page having an class attribute classname in selenium-webdriver


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

												public class Locators {
													public static void main (String [] args){
														WebDriver driver = new FirefoxDriver();
														driver.get("https://chercher.tech/locator_example");
														// Below line matches with banana button
														driver.findElement(By.className(".banana")).click();
													}
												}
											

tagName

The tagname locator looks for an element in the page having an tagname, like <a>, <button>, <p>, <label>, <div> etc tagname in selenium-webdriver


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

													public class Locators {
														public static void main (String [] args){
															WebDriver driver = new FirefoxDriver();
															driver.get("https://chercher.tech/locator-example");
															// Below line matches with banana button
															driver.findElement(By.className(".banana")).click();
														}
													}
												

Partial Link Text

In some situations, we may need to find links by a portion of the text in a Link Text element. it contains. In such situations, we use Partial Link Text to locate elements.

linktext in selenium-webdriver


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

																public class Locators {
																	public static void main (String [] args){
																		WebDriver driver = new FirefoxDriver();
																		driver.get("https://chercher.tech/locator-example")
																		driver.findElement(By.partialLinkText("Selenium")).click();
																	}
																}
															

CSS Selector in Selenium

CSS Selector is the combination of an element selector and a selector value which identifies the web element within a web page. The composite of element selector and selector value is known as Selector Pattern.

When we don't have an option to choose Id or Name, we should prefer using CSS locators as the best alternative. Read how to
build CSS Selector in Selenium


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

																	public class Locators {
																		public static void main (String [] args){
																			WebDriver driver = new FirefoxDriver();
																			driver.get("https://chercher.tech/locator-example");
																			// # means id, so here below locator points
																			// to element which have id as firstButton
																			driver.findElement(By.cssSelector("#firstButton")).click();
																		}
																	}
																

Single Inheritance in Selenium and java

Good & Reliable Selenium locator

Readability of Locator:

Shorter is better, preferable with a clear unique name/id which describes this unique element on the page.

Feel free to change the code like classes/names/id's to make the locator and the test-code very understandable and readable.

We should avoid using classes or IDs which has more than one space in its value, if the values is having more spaces indirectly means that this locators valus is about to change frequently

Maintainability of locator:

The structure of the locator should be so uniquely good that it does not need to be updated if the location of the element in the page changes.

Unless the functionality changes you should be able to minimize the updating of locators and or tests.

Speed of locator:

When it comes to locators, speed is also important aspect, when we design locators we should give preferences to Id, which are retty fast compared to other locators.

But we cannot say whether xpath is good or CSS at the speed, because the based on the browser the speed of locating an element in selenium changes.

Things to remember when you are using Find Element


1. Use this method to access any single element on the web page.

2. It returns the first matching element of the specified locator.

3. It throws an NoSuchElementException exception when it fails to locate the element( when element is not there).

Syntax : WebElement example = driver.findElement(By.locator("locator")); 

My Experience with findElement()


1. You cannot get other than first element using findElement()

2. Implicitly Wait applicable on findElement()

3. If you are in page level, findElement() will look for the element in page level, it will not look for the element which is present inside a Frame and vice versa


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

										public class FindEle {
											public static void main(String[] args) {
												WebDriver driver = new FirefoxDriver();
												driver.get("https://chercher.tech/practice-page");
												// className locator
												driver.findElement(By.className("className")).click();
												// css locator
												driver.findElement(By.cssSelector(".className")).click();
												// id  locator
												driver.findElement(By.id("cn")).click();
												// link text locator
												driver.findElement(By.linkText("selenium webdriver")).click();
												// partial link text locator
												driver.findElement(By.partialLinkText("webdriver")).click();
												// tagname locator
												driver.findElement(By.tagName("a")).click();
												// xpath locator
												driver.findElement(By.xpath("//a")).click();
											}
										}
									

Take Web Element Screenshot in selenium

Find Elements

We can use findElement() method to find single element but sometime we may want to perform operation on more than one element, in those cases we cannot write findElement() method for all the elements.

In selenium we have a findElements() method which can return multiple elements matching with given locator, findElements() returns List<WebElement>.

Note : findElements() returns List<WebElement> not WebElements

Things to remember when you are using Find Elements


1. We don’t use it frequently

2. It gives back the whole list of all(not all but all the elements which are loaded by that time) the elements matching the specified locator.

3. If the element doesn’t exist or not available on the page then, the return value will be an empty list.

4.It will not throw 'NoSuchElementFoundException' in case element is not present

Syntax : List<WebElement> elems = driver.findElements(By.locator("locator")); 

My Experience with findElements()


1. We can use findElements to mimic findElement(), example covered below

2. You can retrieve elements as List or ArrayList.

3. User will be allowed to perform only list operations on the return value, we have to iterate through each item to perform webelement operations

4. implicitlyWait applicable on findElements on special occasion, please visit implicitlyWait for more details

5. If you are in page level, findElements() will look for the element in page level, it will not look for the element which is present inside a Frame and vice versa


											import java.util.List;
											import org.openqa.selenium.By;
											import org.openqa.selenium.WebDriver;
											import org.openqa.selenium.WebElement;
											import org.openqa.selenium.firefox.FirefoxDriver;

											public class FindElems {

												public static void main(String[] args) {
													WebDriver driver = new FirefoxDriver();
													driver.get("https://chercher.tech/practice-page");

													// xpath locator
													List<WebElement> elems = driver.findElements(By.xpath("//input[@id='all']"));
													// go through one by one element in elems list
													for (int i = 0; i < elems.size(); i++) {
														elems.get(i).click();
													}
												}
											}

										

Mimic findElement() using findElements()

In below code examples we will see how to select first checkbox in Selenium Webdriver Practice Page page using findElement and findElements


													// findElement Example
													import org.openqa.selenium.By;
													import org.openqa.selenium.WebDriver;
													import org.openqa.selenium.firefox.FirefoxDriver;

													public class FindElem {

														public static void main(String[] args) {
															WebDriver driver = new FirefoxDriver();
															driver.get("https://chercher.tech/practice-page");

															// select first checkbox
															driver.findElement(By.xpath("//input[@id='all']")).click();
														}
													}

												


With findElements()

													// findElements Example
													import org.openqa.selenium.By;
													import org.openqa.selenium.WebDriver;
													import org.openqa.selenium.firefox.FirefoxDriver;

													public class FindElems {

														public static void main(String[] args) {
															WebDriver driver = new FirefoxDriver();
															driver.get("https://chercher.tech/practice-page");

															// select first checkbox
															driver.findElements(By.xpath("//input[@id='all']")).get(0).click();
														}
													}

												

Assess yourself


1. Try to write a program to select alternate checkbox on Selenium Webdriver Practice Page page under "Checkbox Section"

2. Try to check fourth checkbox on Selenium Webdriver Practice Page page under "Checkbox Section"

3. Try to store all the check boxes using ArrayList rather than List

4. Try to select bottom 3 checkboxes on Selenium Webdriver Practice Page page under "Checkbox Section"

About Author

Myself KarthiQ, I am the author of this blog, I know ways to write a good article but some how I donot have the skills to make it to reach people, would you like help me to reach more people By sharing this Article in the social media.

Share this Article Facebook
Comment / Suggestion Section
Point our Mistakes and Post Your Suggestions
Copyright © CherCher Tech