0
0
Selenium Pythontesting~3 mins

Why XPath with contains and starts-with in Selenium Python? - Purpose & Use Cases

Choose your learning style9 modes available
The Big Idea

What if your tests could find buttons even when their names change a little?

The Scenario

Imagine you have a huge webpage with many buttons and links. You want to click a button, but its exact name changes often, like 'Submit Form 1', 'Submit Form 2', and so on. Manually searching for the exact button each time is like finding a needle in a haystack.

The Problem

Manually writing exact names or full paths for each element is slow and breaks easily when the page changes. You might miss some buttons or click the wrong one, causing errors and frustration.

The Solution

Using XPath with contains and starts-with lets you find elements by parts of their names or attributes. This means your tests keep working even if the full text changes, making your automation smarter and more reliable.

Before vs After
Before
driver.find_element(By.XPATH, "//button[text()='Submit Form 1']")
After
driver.find_element(By.XPATH, "//button[contains(text(), 'Submit Form')]")
What It Enables

This lets you write flexible tests that adapt to small changes in the webpage without breaking.

Real Life Example

When testing a shopping site, product names might change slightly. Using contains helps you find the 'Add to Cart' button even if the product name updates.

Key Takeaways

Manual exact matching is fragile and slow.

contains and starts-with make element finding flexible.

Tests become more reliable and easier to maintain.