0
0
Selenium Pythontesting~10 mins

Find element by XPath in Selenium Python - Test Execution Trace

Choose your learning style9 modes available
Test Overview

This test opens a web page, finds a button using its XPath locator, clicks it, and verifies that a confirmation 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 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()
Execution Trace - 6 Steps
StepActionSystem StateAssertionResult
1Test starts and Chrome browser opensChrome browser window is open and ready-PASS
2Browser navigates to 'https://example.com/testpage'Page loads fully with button and confirmation elements present-PASS
3Wait until button with XPath '//button[@id="submit-btn"]' is clickable and find itButton element is found and ready to be clicked-PASS
4Click the button found by XPathButton is clicked, page reacts accordingly-PASS
5Wait until confirmation message with XPath '//div[@id="confirmation"]' is visibleConfirmation message element is visible on the pageCheck that confirmation text equals 'Submission successful'PASS
6Test ends and browser closesBrowser window is closed-PASS
Failure Scenario
Failing Condition: The button with the specified XPath is not found or not clickable within 10 seconds
Execution Trace Quiz - 3 Questions
Test your understanding
Which Selenium method is used to find the button by XPath?
Adriver.find_element(By.XPATH, '//button[@id="submit-btn"]')
Bdriver.find_element_by_id('submit-btn')
Cdriver.find_element(By.CSS_SELECTOR, '#submit-btn')
Ddriver.find_element_by_name('submit-btn')
Key Result
Use explicit waits with WebDriverWait and expected_conditions to reliably find elements by XPath before interacting with them.