Contents
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 below HTML document.
index.html
<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.webdriver.chrome.service import Service
from selenium import webdriver
from selenium.webdriver.common.by import By
service = Service(executable_path="/usr/local/bin/chromedriver")
#initialize web driver
with webdriver.Chrome(service=service) as driver:
#navigate to the url
driver.get('http://127.0.0.1:5500/localwebsite/index.html')
#find elements by name
elements = driver.find_elements(By.NAME, 'xyz')
for element in elements:
print(element.get_attribute("outerHTML"))
Output
<div name="xyz">Div 1</div>
<div name="xyz">Div 3</div>
Summary
In this tutorial of Python Examples, we learned how to find all the elements by given name
attribute, in webpage, using Selenium.