Selenium WebDriver Locators & Element Identification 1 β Questions and Answers
Question 1: Which locator strategy is generally considered the most reliable for identifying web elements in Selenium WebDriver?
- XPath
- ID (Correct answer)
- Class Name
- Tag Name
Correct answer: ID
The ID attribute is unique per page by HTML specification, making it the most stable and reliable locator when available.
Question 2: What method is used to find a single element by its CSS selector in Selenium WebDriver?
- driver.findElements(By.cssSelector("..."))
- driver.findElement(By.css("..."))
- driver.findElement(By.cssSelector("...")) (Correct answer)
- driver.findElement(By.style("..."))
Correct answer: driver.findElement(By.cssSelector("..."))
The correct By class method for CSS selectors is `By.cssSelector()`, using the full compound name.
Question 3: Which By locator would you use to find an element with the HTML attribute `name="username"`?
- By.id("username")
- By.name("username") (Correct answer)
- By.className("username")
- By.tagName("username")
Correct answer: By.name("username")
`By.name()` directly targets the HTML `name` attribute, making it the appropriate locator for this case.
Question 4: What does `driver.findElements()` return when no matching elements are found on the page?
- null
- An empty list (Correct answer)
- NoSuchElementException
- An empty WebElement object
Correct answer: An empty list
`findElements()` (plural) returns an empty `List<WebElement>` when nothing matches, avoiding exceptions.
Question 5: Which XPath expression correctly selects a button element whose exact text content is "Submit"?
- //button[contains(text()="Submit")]
- //button[@text="Submit"]
- //button[text()="Submit"] (Correct answer)
- //button[innerText="Submit"]
Correct answer: //button[text()="Submit"]
The XPath `text()` function retrieves the text node of an element, and `=` performs an exact match.
Question 6: What is the correct Selenium WebDriver syntax to locate an anchor element by its full visible link text?
- driver.findElement(By.linkText("Click Here")) (Correct answer)
- driver.findElement(By.text("Click Here"))
- driver.findElement(By.anchorText("Click Here"))
- driver.findElement(By.href("Click Here"))
Correct answer: driver.findElement(By.linkText("Click Here"))
`By.linkText()` is the dedicated Selenium locator for finding anchor (`<a>`) elements by their exact visible text.
Question 7: Which locator strategy in Selenium WebDriver finds elements when only part of the anchor text is known?
- By.partialText()
- By.containsLinkText()
- By.partialLinkText() (Correct answer)
- By.fuzzyLinkText()
Correct answer: By.partialLinkText()
`By.partialLinkText()` matches anchor elements whose visible text contains the provided substring.
Which locator strategy is generally considered the most reliable for identifying web elements in Selenium WebDriver?