Selenium find element by id to locate element

Selenium find element by id

Selenium find element by id is very useful and popular element locator among the all types of element locators in selenium. If element have ID attribute then it is very easy to find element by id in selenium. Also it is very easy for tester to find id of element with the help of developer tool in chrome.

Expression to find element by id in selenium is : findElement(By.id("id of element")).

How to find id of element?

You can use chrome developer tool to inspect and get id of element as below.

  • Open your desired page in chrome browser.
  • Right click on element and select Inspect from context menu. It will open developer tool highlighting html of selected element.
selenium find element by id

In above image you can see that ID of child1 textbox is child_1. You can use that id in selenium find element by id.

How to find element by id in selenium?

After getting id of element, you can write below given syntax in your test script to locate element by id.
  • WebElement child1Txt= driver.findElement(By.id("child_1"));
Selenium will locate element by it's id child_1 and then next step is to type some text in it. Below given syntax will type text in textbox.
  • child1Txt.sendKeys("test text");
This way you can find element by id in selenium java.

Why id is best locator in selenium

Here are few advantages to locate element by id.
  • Selenium find element very fast using id locator.
  • id is unique identifier of element on page. Most of the time, you will not find same id of 2 elements on same page.
  • You will find id of most of the elements on page.
  • Most of the browsers support id as an identifier. If you use xpath then different browsers use different mechanism to locate element by xpath and sometimes it fails to locate element by xpath in some browsers.

When not to use find element by id in selenium?

If id of element is dynamic and changing every time page reloads then you should use different locator than the name locator. id locator can be used only if it is static.

Selenium find element by id example

import org.openqa.selenium.By;

public class FindByID{

	public static void main(String[] args) {
		
		System.setProperty("webdriver.chrome.driver", "D:\\chromedriver_win32\\chromedriver.exe");  
	    WebDriver driver=new ChromeDriver();  
	      
	    driver.navigate().to("http://only-testing-blog.blogspot.com/2022/11/relationship.html");  
	    
	    //selenium find by id.
	    WebElement child1Txt= driver.findElement(By.id("child_1"));
	    child1Txt.sendKeys("Child name");
	    driver.close();
	}
}
Above given example will find element by id child_1 and then type text Child name in it.

No comments:

Post a Comment