ScreenshotNeo

BlogHow-to

How to Use the Name Locator in Selenium

Use Selenium’s name locator to find elements by their HTML name attribute. Learn the syntax, handle duplicate matches, and troubleshoot common lookup failures.

By the ScreenshotNeo team4 October 20267 min read

Selenium’s name locator finds an element by its HTML name attribute. In Python, use driver.find_element(By.NAME, "newsletter"); the string is the attribute’s value, not the field’s visible label or text. A singular lookup returns the first match. Use find_elements to inspect every match or handle the case where none exist.

1. What the name locator matches

The name locator matches an element’s name attribute. For example, <input name="newsletter"> can be found with the value newsletter. It does not search the element’s displayed label, placeholder, text, or id.

<label for="email">Email address</label>
<input id="email" name="contact_email" type="email">

For that markup, the name locator value is contact_email. Email address is the label text, and email is the ID. The locator guide describes eight traditional strategies: class name, CSS selector, ID, name, link text, partial link text, tag name, and XPath. The right choice depends on whether the value uniquely identifies the intended element and is clear and stable for the test. See Selenium’s locator strategies documentation.

2. Find one element in Python

Install Selenium with pip install selenium. The following script opens a page, finds an element by its name attribute, and prints its tag and value. Replace the example URL and attribute value with those from the page you are testing.

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

options = webdriver.ChromeOptions()
# Uncomment to run Chrome without opening a visible window.
# options.add_argument("--headless=new")

driver = webdriver.Chrome(options=options)
try:
    driver.get("https://example.com/form")
    element = driver.find_element(By.NAME, "newsletter")
    print(element.tag_name, element.get_attribute("value"))
finally:
    driver.quit()

Recent Selenium versions can manage a compatible browser driver through Selenium Manager. If your environment manages browser drivers separately, make sure the installed driver is compatible with the browser. The example assumes the page contains an element named newsletter; it is illustrative, so adapt it to the page under test.

Use a wait when the element appears after page load

When a page renders the target asynchronously, a lookup immediately after navigation can run too early. Wait for the element instead of adding an arbitrary sleep:

from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.support.ui import WebDriverWait

with webdriver.Chrome() as driver:
    driver.get("https://example.com/form")
    element = WebDriverWait(driver, 10).until(
        EC.presence_of_element_located((By.NAME, "newsletter"))
    )
    print(element.tag_name)

presence_of_element_located waits until the element exists in the DOM. If the next action requires it to be visible or clickable, use the corresponding expected condition, such as visibility_of_element_located or element_to_be_clickable.

3. Handle duplicate names and missing matches

Although Selenium’s guidance says a name should generally be unique, real pages can contain multiple elements with the same value. find_element returns the first matching element in the current search context. To inspect all matches, use find_elements; it returns an empty list when nothing matches.

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

with webdriver.Chrome() as driver:
    driver.get("https://example.com/form")
    matches = driver.find_elements(By.NAME, "newsletter")

    if not matches:
        raise LookupError("No element has name='newsletter'")

    print(f"Found {len(matches)} matching elements")
    for index, element in enumerate(matches):
        print(index, element.tag_name, element.get_attribute("type"),
              element.get_attribute("value"))

If there are duplicates, make the search more specific. You can first find a meaningful parent element, then search inside it, or use CSS to combine the name with another attribute:

# Search within a known section of the page.
section = driver.find_element(By.ID, "preferences")
checkbox = section.find_element(By.NAME, "newsletter")

# Or match more than one attribute with CSS.
checkbox = driver.find_element(
    By.CSS_SELECTOR, 'input[name="newsletter"][type="checkbox"]'
)

Use a parent that describes the part of the page containing the intended control. Avoid relying on a list position unless the page’s ordering is itself meaningful and stable.

4. Syntax in Java and JavaScript

The same locator strategy is available in Selenium’s Java and JavaScript bindings. These snippets show the lookup syntax; create and configure the driver using the setup appropriate to your project.

// Java
import org.openqa.selenium.By;
import org.openqa.selenium.WebElement;

WebElement newsletter = driver.findElement(By.name("newsletter"));
// JavaScript (Node.js Selenium WebDriver)
const { By } = require('selenium-webdriver');

const newsletter = await driver.findElement(By.name('newsletter'));

For language-specific setup and API details, see the Selenium documentation for WebDriver. In each binding, pass the exact name attribute value.

5. Choose between name, ID, and CSS

Strategy Use it when Watch for
Name The markup has a useful, stable name value for the control. Names may repeat, especially for grouped controls.
ID A unique, predictable ID identifies the intended element. Some pages generate or change IDs.
CSS selector You need to combine attributes, tag names, or other CSS conditions. Keep the selector readable and tied to meaningful markup.

Selenium’s locator tips generally prefer an ID when it is available, unique, and consistently predictable. A name locator is a direct choice when the page’s name value clearly identifies the control. CSS is useful when one attribute is not enough. No strategy is best for every page; choose one that is understandable and likely to survive routine changes. See Selenium’s locator tips.

6. Common errors and fixes

Symptom Likely cause Fix
NoSuchElementException No element with that name exists in the current search context when the lookup runs. Check the exact name attribute in the DOM, confirm the page or frame is correct, and wait for asynchronous content if needed.
The wrong control is returned More than one element shares the name; singular lookup returns the first match. Inspect find_elements results, then narrow the search to a parent or use a CSS selector with additional conditions.
The visible label appears correct, but lookup fails The label text is not the element’s name attribute. Inspect the input element and use its actual name; use another locator strategy if the desired text is the reliable identifier.
The element is present but an action fails It may not yet be visible, enabled, or ready for interaction. Wait for visibility or clickability as appropriate, then perform the action.
Lookup fails inside an iframe The driver is searching the top-level document, not the frame’s document. Switch to the correct frame before locating the element, then switch back with driver.switch_to.default_content() when done.

7. Reliability and performance notes

  • Prefer a meaningful, stable attribute. A useful name makes the test easy to read, but page markup can contain duplicate values or change during redesigns.
  • Wait for the condition you need. A presence wait is suitable for DOM existence; visibility and clickability waits better match interactions.
  • Keep duplicate handling explicit. A plural lookup makes ambiguity visible and lets the test report a useful failure instead of silently selecting the first match.
  • Keep browser sessions bounded. Close the driver in a finally block or use a context manager so the browser process is cleaned up after success or failure.
  • Cost depends on your environment. Selenium itself is an open-source browser automation project; browser execution can still consume CI minutes and machine resources. No general execution time or cost is guaranteed by the locator strategy.

8. Or skip the browser setup

If the goal is to capture a page as an image or PDF rather than interact with its form controls, ScreenshotNeo provides a website screenshot API. One GET request returns an image or PDF. See the ScreenshotNeo API documentation for request options.

curl -G "https://api.screenshotneo.com/v1/shot" \
  -d access_key=YOUR_API_KEY \
  --data-urlencode url=https://stripe.com \
  -o shot.webp
import requests

r = requests.get(
    "https://api.screenshotneo.com/v1/shot",
    params={"access_key": "YOUR_API_KEY", "url": "https://stripe.com"},
    timeout=90,
)
r.raise_for_status()
open("shot.webp", "wb").write(r.content)
const q = new URLSearchParams({
  access_key: 'YOUR_API_KEY',
  url: 'https://stripe.com'
});
const res = await fetch(`https://api.screenshotneo.com/v1/shot?${q}`);
if (!res.ok) throw new Error(`Screenshot request failed: ${res.status}`);
const bytes = Buffer.from(await res.arrayBuffer());
await import('node:fs/promises').then(fs => fs.writeFile('shot.webp', bytes));

ScreenshotNeo removes cookie banners, newsletter popups, and chat widgets before capture. Bot checks, blank pages, failed loads, and cache hits are never billed, and the response reports the page verdict and billing status in headers. Its MCP server lets AI agents take screenshots. The free plan includes 1,000 screenshots per month with no card; paid plans start at $5 for 3,000. Sign up for 1,000 free screenshots a month, with no card.

9. FAQ

Does the name locator find an element by its label?

No. It matches the element’s name attribute. A label may be connected to the input through a for attribute, but its text is a separate value.

Does find_element(By.NAME, ...) return every match?

No. It returns the first match in the current search context. Use find_elements to get all matches.

Can I use a name locator for a button or checkbox?

Yes, if the element has the name attribute you specify. The locator strategy is based on the attribute, not the element’s type.