How to find Elements by Tag Name using Selenium?

Find Elements by Tag Name

To find all HTML Elements that has a given tag name in a document, using Selenium in Python, call find_elements() method, pass By.TAG_NAME as the first argument, and the tag name (of the HTML Elements we need to find) as the second argument.

find_elements(By.TAG_NAME, "tag_name_value")

find_elements() method returns all the HTML Elements, that match the given tag name, as a list.

If there are no elements by given tag name, find_elements() function returns an empty list.

Example

Consider the HTML document at the URL https://pythonexamples.org/tmp/selenium/index-56.html, with the following HTML content.

HTML Webpage

<html>
 <body>
  <p>Paragraph 1</p>
  <div name="xyz">
    <p>Article 1</p>
    <a href="/tmp/article-1/">Read More</a>
  </div>
  <div name="xyz">
    <p>Article 2</p>
    <a href="/tmp/article-2/">Read More</a>
</div>
 </body>
</html>
Copy

In the following program, we will find all the HTML elements whose tag name is 'p', using find_elements() method, and print those elements to the console.

Python Program (Selenium)

from selenium import webdriver
from webdriver_manager.chrome import ChromeDriverManager
from selenium.webdriver.chrome.service import Service as ChromeService
from selenium.webdriver.common.by import By

# Setup chrome driver
driver = webdriver.Chrome(service=ChromeService(ChromeDriverManager().install()))

# Navigate to the url
driver.get('https://pythonexamples.org/tmp/selenium/index-56.html')

# Find elements whose Tag Name = "p", i.e., paragraphs
my_elements = driver.find_elements(By.TAG_NAME, 'p')
for element in my_elements:
    print(element.get_attribute("outerHTML"))

# Close the driver
driver.quit()
Copy

Output

<p>Paragraph 1</p>
<p>Article 1</p>
<p>Article 2</p>

Summary

In this Python Selenium tutorial, we learned how to find all the elements by given tag name, present in the webpage, using Selenium.

Related Tutorials

Quiz on Selenium

Q1. Which of the following is not a popular web driver used in Selenium Python?

Not answered

Q2. What is the method used to find web elements in Selenium Python?

Not answered

Q3. Which of the following is not a method to wait for a web element to load in Selenium Python?

Not answered

Q4. What is the method used to switch to a different frame in Selenium Python?

Not answered

Q5. Which of the following is not a commonly used web element locator in Selenium Python?

Not answered
Code copied to clipboard successfully 👍