Discover how a few smart XPath tricks can save you hours of tedious clicking!
Why XPath functions (contains, starts-with) in Selenium Java? - Purpose & Use Cases
Imagine you are testing a website with hundreds of buttons and links. You need to find a button that has a label starting with 'Submit' or contains the word 'Next'. Doing this by clicking and checking each element manually is like searching for a needle in a haystack.
Manually checking each element is slow and tiring. You might miss some buttons or click the wrong ones. It's easy to make mistakes, and repeating this every time the page changes wastes a lot of time.
XPath functions like contains() and starts-with() let you write smart queries to find elements by partial text or attributes. This means you can quickly and accurately select the right elements without checking each one manually.
driver.findElement(By.xpath("//button[text()='Submit Form']"));driver.findElement(By.xpath("//button[starts-with(text(),'Submit')]"); driver.findElement(By.xpath("//a[contains(text(),'Next')]");
With these XPath functions, you can easily find elements even if their text changes slightly, making your tests more flexible and reliable.
On a shopping site, the 'Add to Cart' button might say 'Add to Cart Now' or 'Add to Cart - Limited Offer'. Using starts-with() or contains() helps your test find the button no matter the exact text.
Manual element search is slow and error-prone.
XPath functions contains() and starts-with() simplify locating elements by partial text.
These functions make tests more flexible and easier to maintain.