0
0
Selenium Pythontesting~5 mins

Find element by name in Selenium Python

Choose your learning style9 modes available
Introduction

Finding elements by their name attribute helps you interact with web page parts easily, like filling forms.

When you want to enter text into a form field identified by its name.
When you need to click a button or checkbox that has a name attribute.
When automating login forms where username or password fields have name attributes.
When verifying if a specific input field exists on a page by its name.
When multiple elements share the same name and you want to select the first one.
Syntax
Selenium Python
element = driver.find_element(By.NAME, "element_name")

Use By.NAME to specify you are searching by the name attribute.

Replace "element_name" with the actual name value of the element.

Examples
Finds the input field where the name attribute is 'username'.
Selenium Python
username_input = driver.find_element(By.NAME, "username")
Finds the button with the name 'submit' to click it later.
Selenium Python
submit_button = driver.find_element(By.NAME, "submit")
Finds a checkbox input named 'agree_terms' to check or uncheck.
Selenium Python
checkbox = driver.find_element(By.NAME, "agree_terms")
Sample Program

This script opens a simple HTML form in the browser, finds elements by their name attributes, and prints their tag names.

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

# Setup WebDriver (make sure the driver executable is in PATH)
driver = webdriver.Chrome()

# Open a simple test page with a form
html = '''
<html>
  <body>
    <form>
      <input type="text" name="username" />
      <input type="password" name="password" />
      <input type="submit" name="login" value="Login" />
    </form>
  </body>
</html>
'''

# Encode the HTML content to be used in data URL
encoded_html = urllib.parse.quote(html)

# Load the HTML content using data URL
driver.get("data:text/html;charset=utf-8," + encoded_html)

# Find the username input by name
username_field = driver.find_element(By.NAME, "username")
print(f"Found element with name 'username': tag name is {username_field.tag_name}")

# Find the login button by name
login_button = driver.find_element(By.NAME, "login")
print(f"Found element with name 'login': tag name is {login_button.tag_name}")

# Close the browser
driver.quit()
OutputSuccess
Important Notes

Always ensure the element with the given name exists, or Selenium will raise an error.

Use find_elements(By.NAME, "name") to get a list if multiple elements share the same name.

Make sure your WebDriver is set up correctly and matches your browser version.

Summary

Use find_element(By.NAME, "name") to locate elements by their name attribute.

This method is useful for interacting with form fields and buttons.

Always handle cases where the element might not be found to avoid errors.