Test Overview
This test opens a web page, finds a button using its XPath locator, clicks it, and verifies that a confirmation message appears.
This test opens a web page, finds a button using its XPath locator, clicks it, and verifies that a confirmation message appears.
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 TestFindElementByXPath(unittest.TestCase): def setUp(self): self.driver = webdriver.Chrome() self.driver.get('https://example.com/testpage') def test_click_button_by_xpath(self): driver = self.driver wait = WebDriverWait(driver, 10) # Find the button using XPath button = wait.until(EC.element_to_be_clickable((By.XPATH, '//button[@id="submit-btn"]'))) button.click() # Verify confirmation message appears confirmation = wait.until(EC.visibility_of_element_located((By.XPATH, '//div[@id="confirmation"]'))) self.assertEqual(confirmation.text, 'Submission successful') def tearDown(self): self.driver.quit() if __name__ == '__main__': unittest.main()
| Step | Action | System State | Assertion | Result |
|---|---|---|---|---|
| 1 | Test starts and Chrome browser opens | Chrome browser window is open and ready | — | PASS |
| 2 | Browser navigates to 'https://example.com/testpage' | Page loads fully with button and confirmation elements present | — | PASS |
| 3 | Wait until button with XPath '//button[@id="submit-btn"]' is clickable and find it | Button element is found and ready to be clicked | — | PASS |
| 4 | Click the button found by XPath | Button is clicked, page reacts accordingly | — | PASS |
| 5 | Wait until confirmation message with XPath '//div[@id="confirmation"]' is visible | Confirmation message element is visible on the page | Check that confirmation text equals 'Submission successful' | PASS |
| 6 | Test ends and browser closes | Browser window is closed | — | PASS |
driver.find_element(By.XPATH, "//button[@id='submit']")find_element returns the first matching element found by the locator.//button[@id='submit'] selects button elements with attribute id='submit'.driver.find_element(By.XPATH, xpath_string).<input name='search'> element?element = driver.find_element(By.XPATH, "//input[@name='search']") print(element.tag_name)
input tag, so element.tag_name returns "input".element = driver.find_element(By.XPATH, "//div[@class='content']") print(element.text)
<div class='content'> elements.div.content exist, only the first is found and printed, others ignored.driver.find_element(By.XPATH, xpath)?text()='Submit' matches elements whose text content is exactly 'Submit'.Pass the test and this pattern moves unknown