0
0
Selenium Pythontesting~15 mins

XPath with text() in Selenium Python - Build an Automation Script

Choose your learning style9 modes available
Verify button click using XPath with text()
Preconditions (1)
Step 1: Open the web page at 'https://example.com/sample-form'
Step 2: Locate the button element using XPath with text() matching 'Submit'
Step 3: Click the 'Submit' button
Step 4: Verify that the page URL changes to 'https://example.com/form-submitted'
✅ Expected Result: The 'Submit' button is found and clicked successfully, and the page navigates to the expected URL.
Automation Requirements - Selenium with Python
Assertions Needed:
Verify the button is located using XPath with text()
Verify the button click leads to the expected URL
Best Practices:
Use explicit waits to wait for the button to be clickable
Use By.XPATH locator with text() function
Avoid hardcoded sleeps
Use clear and descriptive variable names
Automated Solution
Selenium Python
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

# Initialize the Chrome driver
with webdriver.Chrome() as driver:
    driver.get('https://example.com/sample-form')

    wait = WebDriverWait(driver, 10)

    # Wait until the button with text 'Submit' is clickable
    submit_button = wait.until(
        EC.element_to_be_clickable((By.XPATH, "//button[text()='Submit']"))
    )

    # Click the button
    submit_button.click()

    # Wait until URL changes to expected
    wait.until(EC.url_to_be('https://example.com/form-submitted'))

    # Assert the URL is correct
    assert driver.current_url == 'https://example.com/form-submitted', f"Expected URL to be 'https://example.com/form-submitted' but got {driver.current_url}"

This script uses Selenium WebDriver with Python to automate the test case.

First, it opens the sample web page.

Then it waits explicitly for the button with the exact text 'Submit' using XPath //button[text()='Submit']. This ensures the element is present and clickable.

After locating the button, it clicks it.

Then it waits until the URL changes to the expected URL https://example.com/form-submitted.

Finally, it asserts that the current URL matches the expected URL, confirming the navigation happened correctly.

Using explicit waits avoids timing issues and makes the test reliable.

Common Mistakes - 3 Pitfalls
Using hardcoded sleep instead of explicit waits
Using XPath without text() to locate the button
Not verifying the URL after clicking the button
Bonus Challenge

Now add data-driven testing with 3 different button texts: 'Submit', 'Send', 'Confirm'. Verify each button click navigates to its respective URL.

Show Hint