Selenium Locators

1. What are Locators in Selenium Java?

  • Locators in Selenium Java are mechanisms used to identify and locate web elements on a web page. These elements could be buttons, text fields, links, etc. They are essential for interacting with elements during test automation.

2. Different Types of Locators in Selenium Java:

a. Locate Elements by ID:

  • This locator selects an element based on its unique HTML ID attribute.
  • Example:
    java
    WebElement element = driver.findElement(By.id("elementID"));

b. Locate Elements by Name:

  • This locator selects elements based on their name attribute.
  • Example:
    java
    WebElement element = driver.findElement(By.name("elementName"));

c. Locate Elements by linkText:

  • This locator selects anchor elements (links) based on their exact text.
  • Example:
    java
    WebElement element = driver.findElement(By.linkText("Link Text"));

d. Locate Elements by partialLinkText:

  • This locator selects anchor elements (links) based on partial text match.
  • Example:
    java
    WebElement element = driver.findElement(By.partialLinkText("Partial Link Text"));

e. Locate Elements by tagName:

  • This locator selects elements based on their HTML tag name.
  • Example:
    java
    WebElement element = driver.findElement(By.tagName("tagname"));

f. Locate Elements by Class:

  • This locator selects elements based on their CSS class attribute.
  • Example:
    java
    WebElement element = driver.findElement(By.className("classname"));

g. Locate Elements by CSS tag and ID:

  • This locator selects elements based on CSS selector with tag name and ID attribute.
  • Example:
    java
    WebElement element = driver.findElement(By.cssSelector("tag#id"));

h. Locate Elements by CSS tag and Class:

  • This locator selects elements based on CSS selector with tag name and class attribute.
  • Example:
    java
    WebElement element = driver.findElement(By.cssSelector("tag.classname"));

i. Locate Elements by CSS tag and attribute:

  • This locator selects elements based on CSS selector with tag name and attribute.
  • Example:
    java
    WebElement element = driver.findElement(By.cssSelector("tag[attribute='value']"));

j. Locate Elements by CSS tag, class, and attribute:

  • This locator selects elements based on CSS selector with tag name, class, and attribute.
  • Example:
    java
    WebElement element = driver.findElement(By.cssSelector("tag.classname[attribute='value']"));

k. Locate Elements by XPath:

  • This locator selects elements based on their XPath expression.
  • Example:
    java
    WebElement element = driver.findElement(By.xpath("//xpath_expression"));

Using these locators, testers can efficiently interact with web elements in Selenium Java automation scripts, thereby facilitating robust and reliable testing of web applications.

Followers