Site icon

Locators for Selenium WebDriver (XPath, CSS, ID, LinkText, Name etc)

Different types of Locators:

ID Locator:

DOM:

UserName:  <input id="txtUsername" name="Username" type="text" />
Password:  <input id="txtPassword" autocomplete="off" name="Password" type="password" />
WebElement usernameElement = driver.findElement(By.id("txtUsername"));
WebElement passwordElement = driver.findElement(By.id("txtPassword"));

Name Locator:

DOM:

UserName:  <input id="txtUsername" name="Username" type="text" />
Password:  <input id="txtPassword" autocomplete="off" name="Password" type="password" />
WebElement usernameElement = driver.findElement(By.name("Username"));
WebElement passwordElement = driver.findElement(By.name("Password"));

Class Name Locator:

Example:

WebElement usernameElement = driver.findElement(By.className("DemoClass"));

Link Text Locator:

Links present on a web page can be identified and accessed using an exact or partial match of their link text. Link Text locator is used to access links using their exact link text match. However, if there are multiple links having the same link text, this method will only access the first one.

Example:

<a href="https://makeinjava.com">Downloads</a/>
 driver.findElement(By.linkText("Downloads")).click()

Partial Link Text Locator:

Links present on a web page can be identified and accessed using an exact or partial match of their link text. Partial Link Text locator is used to access links using portion of their link text. However, if there are multiple links having the same partial link text, this method will only access the first one.

Example:

<a href="https://makeinjava.com">Downloads</a/>
 driver.findElement(By.partialLinkText("Downloa")).click()

Tag Name Locator:

Example:

driver.get("http://www.google.com");
 List  list = driver.findElements(By.tagName("a"));
 System.out.println("Count of links:"+list.size());
 for(int i = 0; i < list.size(); i++){
 System.out.println(list.get(i).getText());
 }

CSS Selector Locator:

CSS selectors are used to style the content of web pages. This also helps us in identifying one or more elements on web page, when elements are not found by the general locators like id, class, name etc. CSS selector makes the execution of script faster as compared to XPath locator . CSS selector locator is considered as the best way to locate complex elements on web page.

Syntax:

CSS = tagname#id
CSS = tagname.className
CSS = tagname[attribute='value']

XPATH Selector Locator:

Syntax:

 Xpath=//tagname[@attribute='value']
 Xpath=//*[contains(@attribute,'value')] 
Exit mobile version