Locating Strategy by ID

In this tutorial, we will discuss on locating Strategy by ID. Locating strategy by ID is deals with ID of the web page. ID is generally known as unique id which is preceded by #. Below screenshot is showing ID of the date element in home page of TestingLPoint.

Locating Strategy by ID

One thing you can think that from where you can find the ID Element. Yes, by inspect element of the web page you will able to see HTML code of that page. You can see the Id in following way in inspect element.

<html>
  <body>
    <form>
      User Name: <input id= "name" name="username" type="text"/>
      Password: <input name="password" type="password"/>
      <input name="submit" type="submit" value="Proceed!"/>
    </form>
  </body>
</html>

 Syntax: : driver.findElement(By.id (<"id of the element">))  

The main advantage of using ID locator is the uniqueness. ID is unique and there are no chance of finding several element. But this will work perfect if you have the fixed ID in you web page. If your ID is changing or generate dynamically then this locator strategy will not be a good option for

Locating web elements in WebDriver is performed with the help of findElement() and findElements() method.

Scenario with Example:

import org.openqa.selenium.By; 
import org.openqa.selenium.WebDriver; 
import org.openqa.selenium.WebElement; 
import org.openqa.selenium.chrome.ChromeDriver;   
public class Locator_By_ID {   
public static void main(String[] args) 
{ 
WebDriver driver= new ChromeDriver() ; 
driver.manage().window().maximize(); 
driver.get("https://www.testinglpoint.com"); 
date_link=driver.findElement(By.id("date"));

Leave a Reply

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