0
0
Selenium Pythontesting~10 mins

XPath with contains and starts-with in Selenium Python - Test Execution Trace

Choose your learning style9 modes available
Test Overview

This test opens a webpage and uses XPath with contains() and starts-with() functions to find elements. It verifies that the correct elements are found and their text matches expected values.

Test Code - Selenium
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
import unittest

class TestXPathFunctions(unittest.TestCase):
    def setUp(self):
        self.driver = webdriver.Chrome()
        self.driver.get('https://example.com/testpage')

    def test_xpath_contains_and_startswith(self):
        driver = self.driver
        wait = WebDriverWait(driver, 10)

        # Find element where attribute contains 'submit'
        submit_button = wait.until(EC.presence_of_element_located((By.XPATH, "//button[contains(@id, 'submit')]")))
        self.assertEqual(submit_button.text, 'Submit')

        # Find element where attribute starts-with 'user'
        username_input = wait.until(EC.presence_of_element_located((By.XPATH, "//input[starts-with(@name, 'user')]")))
        self.assertEqual(username_input.get_attribute('placeholder'), 'Enter username')

    def tearDown(self):
        self.driver.quit()

if __name__ == '__main__':
    unittest.main()
Execution Trace - 5 Steps
StepActionSystem StateAssertionResult
1Test starts and Chrome browser opensBrowser window is open and ready-PASS
2Browser navigates to 'https://example.com/testpage'Page loads with test elements visible-PASS
3Wait until button with id containing 'submit' is present using XPath contains()Button element with id like 'btn-submit' is foundCheck button text equals 'Submit'PASS
4Wait until input with name starting with 'user' is present using XPath starts-with()Input element with name like 'username' is foundCheck input placeholder attribute equals 'Enter username'PASS
5Browser closes and test endsBrowser window closed-PASS
Failure Scenario
Failing Condition: Element with XPath using contains() or starts-with() is not found within timeout
Execution Trace Quiz - 3 Questions
Test your understanding
Which XPath function is used to find elements with attribute values that include a specific substring?
Acontains()
Bstarts-with()
Cends-with()
Dequals()
Key Result
Using XPath functions like contains() and starts-with() helps find elements flexibly by partial attribute matching, making tests more robust to small changes in attribute values.