0
0
Selenium Pythontesting~15 mins

Find element by tag name in Selenium Python - Build an Automation Script

Choose your learning style9 modes available
Verify presence of header element by tag name
Preconditions (2)
Step 1: Open the browser and navigate to 'https://example.com'
Step 2: Locate the first <h1> tag element on the page using tag name locator
Step 3: Verify that the <h1> element is displayed on the page
✅ Expected Result: The <h1> element is found and visible on the page
Automation Requirements - Selenium with Python
Assertions Needed:
Assert that the <h1> element is not None
Assert that the <h1> element is displayed (visible)
Best Practices:
Use explicit waits to wait for the element to be present
Use By.TAG_NAME locator strategy
Handle exceptions if element is not found
Close the browser after test execution
Automated Solution
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
from selenium.common.exceptions import TimeoutException

# Initialize the Chrome WebDriver
with webdriver.Chrome() as driver:
    driver.get('https://example.com')

    try:
        # Wait up to 10 seconds for the <h1> element to be present
        h1_element = WebDriverWait(driver, 10).until(
            EC.presence_of_element_located((By.TAG_NAME, 'h1'))
        )

        # Assert the element is displayed
        assert h1_element.is_displayed(), 'The <h1> element is not visible on the page.'

        print('Test Passed: <h1> element found and visible.')

    except TimeoutException:
        print('Test Failed: <h1> element not found within 10 seconds.')
        assert False, 'The <h1> element was not found on the page.'

This script uses Selenium WebDriver with Python to automate the test case.

First, it opens the browser and navigates to the specified URL.

Then, it waits explicitly up to 10 seconds for the <h1> tag element to appear on the page using WebDriverWait and presence_of_element_located with By.TAG_NAME.

Once found, it asserts that the element is visible using is_displayed(). If the element is not found within the timeout, it catches the TimeoutException and fails the test.

The with statement ensures the browser closes automatically after the test.

Common Mistakes - 4 Pitfalls
Using find_element without explicit wait
{'mistake': 'Using incorrect locator like By.ID instead of By.TAG_NAME', 'why_bad': "The locator won't find the element if the tag name is required, causing test failure.", 'correct_approach': 'Use By.TAG_NAME locator when searching elements by their tag name.'}
Not checking if the element is displayed before asserting
Not closing the browser after test execution
Bonus Challenge

Now add data-driven testing to verify presence of multiple tag names: 'h1', 'p', and 'footer' on the page.

Show Hint