๐Ÿš€ Mastering Selenium WebDriver 4.0: New Locator Strategies for Easier Automation! ๐Ÿ› ๏ธ

Pavan Kumar
2 min readSep 18, 2024

--

Selenium WebDriver 4.0 brings exciting new locator strategies that make finding web elements much easier and more intuitive. These new methods allow you to locate elements relative to others, making your automation scripts more natural and easier to maintain. Letโ€™s dive into these fresh locators that simplify our work! ๐ŸŽ‰

๐Ÿ” New Locator Strategies:

  • above: Find elements located above a given element.
  • below: Locate elements below a specific element.
  • toLeftOf: Find elements to the left of another.
  • toRightOf: Locate elements to the right of a target element.
  • near: Find elements that are within 50px of a given element.

๐Ÿง Why Are These Helpful?

Before, youโ€™d have to define elements inside a specific container like a <div> with an id or use complex XPath/CSS selectors. But now, with these new strategies, you can describe and locate elements in a more human-friendly way. Think of it as saying, "Find the element above this one," rather than hunting inside a deeply nested structure. ๐Ÿง‘โ€๐Ÿ’ป

๐Ÿค– How to Use Them?

Letโ€™s walk through some examples in Java:

๐Ÿ‘‰ Example 1: Locating an element above another

WebElement passwordField = driver.findElement(By.id("password"));
WebElement email = driver.findElement(with(By.tagName("input")).above(passwordField));

๐Ÿ‘‰ Example 2: Finding an element below another

WebElement emailAddressField = driver.findElement(By.id("email"));
WebElement passwordField = driver.findElement(with(By.tagName("input")).below(emailAddressField));

๐Ÿ‘‰ Example 3: Finding an element to the left of another

Scenario: Locate the โ€œCancelโ€ button to the left of the โ€œSubmitโ€ button.

WebElement submitButton = driver.findElement(By.id("submit"));
WebElement cancelButton = driver.findElement(with(By.tagName("button")).toLeftOf(submitButton));

๐Ÿ‘‰ Example 4: Finding an element to the right of another

Scenario: Locate the โ€œSubmitโ€ button to the right of the โ€œCancelโ€ button.

WebElement cancelButton = driver.findElement(By.id("cancel"));
WebElement submitButton = driver.findElement(with(By.tagName("button")).toRightOf(cancelButton));

๐Ÿ‘‰ Example 5: Using near to locate elements within 50px of another

WebElement emailLabel = driver.findElement(By.id("lbl-email"));
WebElement emailField = driver.findElement(with(By.tagName("input")).near(emailLabel));

๐ŸŽฏ Conclusion:

These new locator strategies in Selenium WebDriver 4.0 make automation scripts more readable and natural. They save time, reduce complexity, and help you focus on writing better test cases. So go ahead and give these new locators a try! ๐Ÿš€

Happy Testing! ๐Ÿ’ปโœจ

--

--

Pavan Kumar
Pavan Kumar

Written by Pavan Kumar

8+ years of Testing experience in automation using Selenium (Java). Expertise in API and Performance testing . Interested in Full Stack Development

No responses yet