0
0
Selenium Pythontesting~5 mins

Find element by tag name in Selenium Python

Choose your learning style9 modes available
Introduction

Finding elements by tag name helps you locate parts of a webpage using their HTML tags, like buttons or paragraphs.

You want to click the first button on a page.
You need to check all paragraphs for specific text.
You want to count how many images are on a page.
You want to verify if a header tag exists.
You want to extract all links by finding all 'a' tags.
Syntax
Selenium Python
element = driver.find_element(By.TAG_NAME, 'tagname')
elements = driver.find_elements(By.TAG_NAME, 'tagname')

Use find_element to get the first matching element.

Use find_elements to get a list of all matching elements.

Examples
Finds the first <button> element on the page.
Selenium Python
button = driver.find_element(By.TAG_NAME, 'button')
Finds all <p> elements and stores them in a list.
Selenium Python
all_paragraphs = driver.find_elements(By.TAG_NAME, 'p')
Finds the first image element on the page.
Selenium Python
first_image = driver.find_element(By.TAG_NAME, 'img')
Sample Program

This script opens a simple webpage with headings, paragraphs, and a button. It finds the first paragraph, counts all paragraphs, and finds the button, printing their texts.

Selenium Python
from selenium import webdriver
from selenium.webdriver.common.by import By

# Start the browser
with webdriver.Chrome() as driver:
    # Open a simple webpage
    driver.get('data:text/html,<html><body><h1>Title</h1><p>Paragraph 1</p><p>Paragraph 2</p><button>Click me</button></body></html>')

    # Find the first paragraph
    first_p = driver.find_element(By.TAG_NAME, 'p')
    print('First paragraph text:', first_p.text)

    # Find all paragraphs
    all_p = driver.find_elements(By.TAG_NAME, 'p')
    print('Number of paragraphs:', len(all_p))

    # Find the button
    button = driver.find_element(By.TAG_NAME, 'button')
    print('Button text:', button.text)
OutputSuccess
Important Notes

Tag names are case-insensitive in HTML but use lowercase in Selenium for consistency.

If no element is found, find_element throws an error; find_elements returns an empty list.

Summary

Use find_element(By.TAG_NAME, 'tagname') to get the first element by tag.

Use find_elements(By.TAG_NAME, 'tagname') to get all elements by tag.

This method is simple and useful for common HTML tags like button, p, img, etc.