-->

Software Testing - Selenium Finding Web Elements

The website automation starts with locating and interacting with site items. Selenium offers several ways to find these elements:

findElement(By.id())

The first element on the page that matches the given ID property is located using this function. IDs are unique on the HTML page, which makes it a frequently used selection.

Example:

WebElement submitButton = driver.findElement(By.id("submit"));

findElement(By.name())

The first element with the given name property is found using this technique. When two or more elements share the same name, it's helpful.

Example:

WebElement usernameField = driver.findElement(By.name("username"));

findElement using By.className()

With the given class name, it locates the first element on the page. This is helpful when aiming for CSS classes.

Example:

WebElement button = driver.findElement(By.className("btn"));

findElement(By.tagName())

This technique finds the first element, such as <a>, <div>, or <button>, that has the given tag name.

Example:

WebElement link = driver.findElement(By.tagName("a"));

findElement(By.linkText())

The first link element on the page with the precise link text that has been given is located using this approach.

Example:

WebElement homeLink = driver.findElement(By.linkText("Home"));

findElement(By.partialLinkText())

The first link element containing the given content is located using this approach. When there is a static portion mixed in with the dynamic link text, it works well.

Example:

WebElement readMoreLink = driver.findElement(By.partialLinkText("Read"));

findElement(By.cssSelector())

It allows for more intricate and exact selections by locating the first element that matches the given CSS selector.

Example:

WebElement button = driver.findElement(By.cssSelector(".btn"));

findElement(By.xpath())

To locate the first element that fits the supplied XPath, this technique uses an XPath expression.

Example:

WebElement button = driver.findElement(By.xpath("//button"));