0
0
Selenium Pythontesting~10 mins

Find element by tag name in Selenium Python - Test Execution Trace

Choose your learning style9 modes available
Test Overview

This test opens a web page and finds the first <h1> tag element. It verifies that the text inside the <h1> tag matches the expected heading.

Test Code - Selenium
Selenium Python
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.chrome.options import Options
import unittest

class TestFindElementByTagName(unittest.TestCase):
    def setUp(self):
        options = Options()
        options.add_argument('--headless')
        service = Service()
        self.driver = webdriver.Chrome(service=service, options=options)

    def test_find_h1_by_tag_name(self):
        self.driver.get('https://example.com')
        element = self.driver.find_element(By.TAG_NAME, 'h1')
        self.assertEqual(element.text, 'Example Domain')

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

if __name__ == '__main__':
    unittest.main()
Execution Trace - 6 Steps
StepActionSystem StateAssertionResult
1Test startsTest framework initializes and prepares the test environment-PASS
2Browser opens in headless modeChrome browser instance is launched without UI-PASS
3Navigates to 'https://example.com'Browser loads the Example Domain page with a visible <h1> element-PASS
4Finds element by tag name 'h1' using driver.find_element(By.TAG_NAME, 'h1')The first <h1> element on the page is located-PASS
5Checks that the text of the <h1> element equals 'Example Domain'The element text is 'Example Domain'assertEqual(element.text, 'Example Domain')PASS
6Browser closes and test endsBrowser instance is terminated cleanly-PASS
Failure Scenario
Failing Condition: The <h1> tag is missing or the text inside it does not match 'Example Domain'
Execution Trace Quiz - 3 Questions
Test your understanding
What Selenium method is used to find the <h1> element in this test?
Adriver.find_element(By.TAG_NAME, 'h1')
Bdriver.find_element(By.ID, 'h1')
Cdriver.find_element(By.CLASS_NAME, 'h1')
Ddriver.find_element(By.CSS_SELECTOR, 'h1')
Key Result
Use find_element with By.TAG_NAME to locate elements by their tag. Always verify the element's text to ensure you found the correct element.