0
0
Selenium Pythontesting~10 mins

XPath with text() in Selenium Python - Test Execution Trace

Choose your learning style9 modes available
Test Overview

This test opens a webpage, finds a button using XPath with the text() function, clicks it, and verifies the expected message appears.

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 TestXPathText(unittest.TestCase):
    def setUp(self):
        self.driver = webdriver.Chrome()
        self.driver.get('https://example.com/buttonpage')

    def test_click_button_by_text(self):
        driver = self.driver
        # Wait until the button with exact text 'Click Me' is present
        button = WebDriverWait(driver, 10).until(
            EC.presence_of_element_located((By.XPATH, "//button[text()='Click Me']"))
        )
        button.click()
        # Wait for the message element to appear
        message = WebDriverWait(driver, 10).until(
            EC.presence_of_element_located((By.ID, 'message'))
        )
        self.assertEqual(message.text, 'Button clicked!')

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

if __name__ == '__main__':
    unittest.main()
Execution Trace - 6 Steps
StepActionSystem StateAssertionResult
1Test starts and Chrome browser opensBrowser window is open and navigated to 'https://example.com/buttonpage'-PASS
2Wait until button with text 'Click Me' is present using XPath //button[text()='Click Me']Button with text 'Click Me' is visible on the pageElement located by XPath with exact text 'Click Me'PASS
3Click the button found by XPathButton is clicked, page reacts to click-PASS
4Wait until element with ID 'message' appearsMessage element is visible on the pageElement with ID 'message' is presentPASS
5Check that message text equals 'Button clicked!'Message text is 'Button clicked!'Assert message.text == 'Button clicked!'PASS
6Test ends and browser closesBrowser window is closed-PASS
Failure Scenario
Failing Condition: Button with text 'Click Me' is not found within 10 seconds
Execution Trace Quiz - 3 Questions
Test your understanding
Which XPath expression is used to find the button by its visible text?
A//button[text()='Click Me']
B//button[@id='click']
C//button[contains(text(),'Click')]
D//button[@class='btn']
Key Result
Using XPath with the text() function helps locate elements by their visible text exactly, which is useful when IDs or classes are not reliable.