How to find Elements by Name using Selenium?

Find Elements by Name

To find HTML Elements by name attribute using Selenium in Python, call find_elements() method and pass By.NAME as the first argument, and the name attribute’s value (of the HTML Element we need to find) as the second argument.

find_elements(By.NAME, "name_value")

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

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

Example

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

HTML Webpage

<html>
 <body>
  <div name="xyz">Div 1</div>
  <div name="abc">Div 2</div>
  <div name="xyz">Div 3</div>
 </body>
</html>

In the following program, we will find all the HTML elements whose name attribute has a value of 'xyz', 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-54.html')

# Find elements by name attribute
my_elements = driver.find_elements(By.NAME, 'xyz')
for element in my_elements:
    print(element.get_attribute("outerHTML"))

# Close the driver
driver.quit()

Output

<div name="xyz">Div 1</div>
<div name="xyz">Div 3</div>

Summary

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

Related Tutorials

Quiz on Selenium

Q1. Which of the following is not a commonly used assertion method in Selenium Python?

Not answered

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

Not answered

Q3. What is the method used to take a screenshot in Selenium Python?

Not answered

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

Not answered

Q5. What is the method used to select a value from a drop-down list in Selenium Python?

Not answered
Code copied to clipboard successfully 👍