What are Locators?
Selenium uses locators to interact with the elements on the webpage.
Different Types of Locators
- XPath
- CssSelector
- ID
- Name
- ClassName
- LinkText
- Partial LinkText
- TagName
XPath and CSS selectors are the most often used locators in automated testing. When the DOM structure does not change regularly, the terms Name, ID, and ClassName are utilized.
XPath and CssSelectors provide the advantage of being able to locate the HTML DOM structure even without a ClassName, ID, or Name. XPath allows for traversing both forwards and backward in the HTML DOM, whereas CssSelectors only allow for traversing forwards.
Example
package Selenium;
import org.openqa.selenium.By;
import org.openqa.selenium.Keys;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
public class Locators {
public static void main(String[] args) {
System.setProperty("webdriver.chrome.driver", "C:\\temp\\drivers\\chromedriver.exe");
WebDriver driver = new ChromeDriver();
driver.get("https://www.google.com/");
driver.manage().window().maximize();
driver.findElement(By.name("q")).sendKeys("Test Automation Central");
driver.findElement(By.xpath("//*[@name='q']")).sendKeys(Keys.ENTER);
}
}