In our previous post, we have discussed the different locators of selenium, and in this post, we are going to discuss “How we can locate Element By ID locator”.
Selenium ID Locators
ID locators are one of the most popular and famous ways to identify the elements in the web page. As per the W3C standard, every element supposes to be unique, which makes this ID locators one of the reliable locators.
ID locator is considered as one of the safest and fastest locator options and for every automation testers its the first choice when there are multiple-choice to locate the web elements.
Let’s take an example to understand how the ID locator work
Scenario:
- Launch Mozilla Firefox
- Open OrangeHRM On Firefox Browser
- Locate the Enter User Name & Password Text box and enter a username & password Id with using the ID locator.
Code Snippet:
package com.selenium.practice.locator; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.firefox.FirefoxDriver; public class IdLocatorExample { public static void main(String[] args) throws InterruptedException { WebDriver driver; System.setProperty("webdriver.gecko.driver","/Software_Testingo_Practice/Selenium_Practice/Selenium_Practice_PGM/Browser_Driver/geckodriver.exe"); driver=new FirefoxDriver(); driver.get("https://orangehrm-demo-6x.orangehrmlive.com/auth/login"); Thread.sleep(10000); driver.findElement(By.id("txtUsername")).clear(); driver.findElement(By.id("txtPassword")).clear(); driver.findElement(By.id("txtUsername")).sendKeys("Admin"); driver.findElement(By.name("txtPassword")).sendKeys("admin"); driver.findElement(By.id("btnLogin")).click(); } }
If you run the above Java program, then you will find out that OrangeHRM will be launched in the Mozilla Firefox browser, after that we are clear the existing value in the field Username and Password and after that, we are entering the username and password in the text box. I hope this gives you a clear understanding of how Id locator in Selenium works.
But since browsers do not make this thing mandatory that for each element the ID should be unique, developers take advantage of this that’s why for some of the elements in the web page ID is not present as a part of an attribute or due to auto-generated some elements have the same ID. Due to the mentioned issues, wen needs to use the other locators.
Leave a Reply