Q1. What are Locators in Selenium WebDriver? Explain different types.
Answer:
Locators in Selenium are used to identify elements on a web page. Selenium WebDriver interacts with web elements like buttons, text fields, links, checkboxes, etc., using locators. These locators help Selenium scripts perform actions such as click, enter text, select, or retrieve data from elements.
Types of Locators in Selenium WebDriver:
- ID – By.id(“elementId”) – Fastest & most preferred if unique.
- Name – By.name(“elementName”) – Common but not always unique.
- Class Name – By.className(“className”) – Targets elements with a specific class.
- Tag Name – By.tagName(“input”) – Identifies elements by HTML tag.
- Link Text – By.linkText(“FullLinkText”) – Identifies exact anchor link text.
- Partial Link Text – By.partialLinkText(“PartialText”) – Uses partial text of a link.
- XPath – By.xpath(“//tag[@attribute=’value’]”) – Very powerful for complex paths.
- CSS Selector – By.cssSelector(“cssPath”) – Fast & cross-browser friendly.
Q2. What is the difference between findElement() and findElements() in Selenium?
Answer:
Feature | findElement() | findElements() |
Return Type | Returns a single WebElement | Returns a list of WebElements |
If Not Found | Throws NoSuchElementException | Returns an empty list |
Use Case | When targeting one unique element | When multiple elements match the locator |
Example | driver.findElement(By.id(“username”)); | driver.findElements(By.tagName(“input”)); |
👉The Next Questions-2: SELENIUM