Part 1: Ways of Locating Web Elements in Selenium using ID

Hello Folks,

In this post we will learn:
1. What is HTML, Web elements and its attributes.
2. How to locate a web element through its id if any.
3. How to know if you are locating correctly.
4. How to let Selenium webdriver know where is element located.
5. How to know if any web element is displayed or not on web page.
6. How to know if any web element is enabled or not on web page.
7. How to use sendKeys() method.

Why we should locate a web element:

Suppose, you are an employee of Flipkart. You need to test a scenario manually.
Scenario: “You need to search a Samsung A7 mobile on Flipkart website and add it to cart.”

Test steps:
1. Open a browser.
2. Open Flipkart web URL.
3. Find a search “TEXT BOX”.
4. “TYPE” Samsung A7 mobile in text box.
5. “CLICK” on proper option from auto suggestion “LISTS”.
6. Click on required mobile link. Mobile details will be opened in new tab.
7. Click on Add to cart “BUTTON”.
8. Click on cart “IMAGE”.
9. Verify if mobile is shown in cart.

Above steps are very easy to perform when you do it manually because you can visualize elements based on its look and feel.
Now you want to automate above steps using Selenium Webdriver. Let’s do it:
1. We know how to open a browser.
2. We know how to open a URL in opened browser.
3. How to do it? How Selenium will know where is search text box?
4. How Selenium will type in search text box?
You will not able to proceed only after step no 2.

So, concept is you must let Selenium Webdriver know where is the element i.e. locating an web element and how to perform any operation on that.
Before we learn about how to locate web elements, let’s start with basics of HTML.

Basics of HTML:

  • HTML stands for Hyper Text Markup Language which describes structure of a web page. Every web page will have text box, buttons, drop down, lists etc. These are called html elements or web elements.
  • We human being have some properties like name, age, height, weight etc by which they can be identified(Not uniquely but up to some extent). HTML elements also may have properties which are called attributes to web element and by which we can identify that web element.
  • HTML attributes generally appear as name-value pairs, separated by =, and are written within the start tag of an element, after the element’s name. For Ex:
    <tag attribute="value">content to be modified by the tag</tag>

    Where tag names the HTML element type, and attribute is the name of the attribute, set to the provided value.

  • We can view html code of any webpage by:
  1. Right click on web page and select Inspect from context click options.
  2. Press ctrl+shift+i.
  3. Press F12.

How to know html code of a particular web element:

  • Just we need to mouse hover on web element and do right click and select Inspect.
  • For e.g. Open https://www.facebook.com in chrome browser and do right click on Email or Phone text box and select inspect. It will highlight html code for that particular text box only. You will able to see this particular text box where you enter your email id or phone number is an input tag with attributes as id and name. Generally two html elements should not have same ID.

attributes

So , now we know what is HTML element and how to see its attributes.

Types of locators in Selenium Webdriver:

Selenium provides mainly eight types of locators:

  1. Id
  2. Name
  3. LinkText
  4. PartialLinkText
  5. Tag name
  6. Class name
  7. CSS
  8. XPATH

Locating web element using ID:

If any web element has attribute as ID, we can locate that element using its id.

For Example:

In above screenshot, Email or phone text box can be located using id whose value is “email”.

How to check if we are locating correct element and how many web elements have same id:

In Chrome:

Without thinking much, copy the value of ID attribute of text box and click on console. Now type as shown below and press enter:

$x(“//tagname[@id=’value’]”)

eg: $x(“//input[@id=’email’]”)

id checker

  • Expend the result. You will see one field named “length” which says how many web elements have same id in web page or how many elements are located by same id. Mouse hover on line starting from input, it will highlight text box in browser.
  • Follow the same process for Firefox browser as well.

firefox

Now, we know how to locate a web element using its id attribute and verify if it is referring correct element or not.

How to instruct selenium to find web element:

To locate web element through Selenium webdriver,  selenium provides two methods:

  1. WebElement findElement(By by) :
WebDriver driver= new ChromeDriver();
WebElement emailPhoneTextBox= driver.findElement(By.id("Some id"));

If more than one web elements have the same id on currently loaded web page, it will return first element which will be stored(in fact reference address. Will discuss later.) in variable “emailPhoneTextBox”.

2. List findElement(By by):

WebDriver driver= new ChromeDriver();
List allElements= driver.findElements(By.id("Some id"));

If more than one web elements have the same id on currently loaded web page, it will return all the web elements found in a List.  I will discuss soon about difference between findElement() and findElements() method soon.

Now we have instructed driver to find a text box whose id is ’email’.

Check of visibility of web element:

Sometimes, we will come up with scenario where  we will be able to locate web element but it will not be displayed on web page. It will be hidden. If you perform any operation on hidden element you will get ElementNotVisibleException. So, it is a good practice to check if element is displayed or not before performing any action on it. For this we have method isDisplayed() which is called on web element for which we want to check if it is displayed or not. It return boolean. If element is visible it returns true otherwise false.

Check of activeness of web element:

You will see sometimes. element is displayed, but it is not active/enable.You can not type in a text box if it is disable. So it is again a good practice to check if element is enable or not before typing. Its return type is boolean. It returns true if element is enable otherwise false.

How to type in text box:

We can type in a text box using sendKeys() method. We need to call sendKeys() method on element on which we can type. Syntax is as below:

emailPhoneTextBox.sendKeys(“amod.mahajan@hotmail.com”);

Note: We can call sendKeys() method on type of web elements where we can type. We can not call it on a button.

So, we have located text box and typed. But how to check whether whatever we have sent, is typed correctly there?

We have another method called getAttribute(String arg) which can be used to get text typed in to text box. Syntax is as below:

String typedValue= emailTextBox.getAttribute(“value”);

Java code:


import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;

public class FacebookLogin {

	public static void main(String[] args) {
		
		// Setting browser driver property 
		System.setProperty("webdriver.chrome.driver", "./exefiles/chromedriver.exe");
		// Opening chrome browser
		WebDriver driver= new ChromeDriver();
		// Opening URL
		driver.get("https://www.facebook.com");
		//Locating a web element using id
		WebElement emailTextBox= driver.findElement(By.id("email"));
		// Checking if element is displayed
		boolean flagDisplayed= emailTextBox.isDisplayed();
		if(flagDisplayed==true)
			System.out.println("Element is displayed.");
		else
			System.out.println("Element is not diplayed.");
		
		// Checking if element is enable
		boolean flagEnable= emailTextBox.isEnabled();
		if(flagEnable==true)
			System.out.println("Element is displayed.");
		else
			System.out.println("Element is not diplayed.");
		// Typing in text box
		if(flagDisplayed== true && flagEnable==true )
		{
			emailTextBox.sendKeys("amod.mahajan@hotmail.com");
			// Retrieving typed value
			String typedValue= emailTextBox.getAttribute("value");
			if(typedValue.equals("amod.mahajan@hotmail.com"))
				System.out.println("Correc value is typed.");
			else
				System.out.println("Incorrect value typed. Typed value is:"+typedValue);
		}
		else
			System.out.println("Element is either not displayed or enabled.");
	}
}

So, I tried to cover many basic and advance concepts and good programming practice as well. I tried to put step by step.

If you like it, please like, comment and share. Feedback are always welcomed.

Thank You!!

#HappyLearning

5 thoughts on “Part 1: Ways of Locating Web Elements in Selenium using ID

Leave a Reply

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