ScreenshotNeo

BlogHow-to

How to Locate Elements by Tag Name in Selenium

Find one or all elements by HTML tag in Selenium, with runnable examples, scoped searches, troubleshooting, and guidance on choosing a reliable locator.

By the ScreenshotNeo team4 October 20266 min read

To locate an element by its HTML tag in Selenium, pass the tag name to the binding’s tag-name locator. In Python, use driver.find_element(By.TAG_NAME, "a"); in Java, use driver.findElement(By.tagName("a")). Use the plural finder, such as Python’s find_elements, when you want every matching element.

Write the tag itself—such as a, input, button, or tr—without angle brackets. A tag-name locator matches the element type, not its ID, class, text, or other attributes. The examples below use Selenium’s documented locator APIs. See the Selenium locator documentation and the Selenium element-finding documentation.

Find one element by tag name

The singular finder returns one matching element. If more than one element has that tag, the result is not a way to identify a particular one; use a more specific locator or search within a known parent.

Python

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

# Requires Selenium Python bindings and a configured browser driver.
driver = webdriver.Chrome()
try:
    driver.get("https://example.com")
    first_link = driver.find_element(By.TAG_NAME, "a")
    print(first_link.get_attribute("href"))
finally:
    driver.quit()

Java

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;

public class FindByTag {
    public static void main(String[] args) {
        WebDriver driver = new ChromeDriver();
        try {
            driver.get("https://example.com");
            WebElement firstLink = driver.findElement(By.tagName("a"));
            System.out.println(firstLink.getAttribute("href"));
        } finally {
            driver.quit();
        }
    }
}

C#

using OpenQA.Selenium;
using OpenQA.Selenium.Chrome;

using IWebDriver driver = new ChromeDriver();
try
{
    driver.Navigate().GoToUrl("https://example.com");
    IWebElement firstLink = driver.FindElement(By.TagName("a"));
    Console.WriteLine(firstLink.GetAttribute("href"));
}
finally
{
    driver.Quit();
}

Find all elements with a tag

Use the plural finder to collect all matches. Selenium returns an empty collection when there are no matches, so a zero-result lookup does not by itself raise the missing-element exception raised by the singular finder.

from selenium.webdriver.common.by import By

inputs = driver.find_elements(By.TAG_NAME, "input")
if not inputs:
    print("No input elements found")
else:
    for index, element in enumerate(inputs, start=1):
        print(index, element.get_attribute("type"), element.get_attribute("name"))

For Java, the equivalent is driver.findElements(By.tagName("input")); for C#, use driver.FindElements(By.TagName("input")). Iterate over the returned collection and inspect a relevant property, or narrow the locator, to select the intended element.

Scope the search to a parent

Pages commonly contain many elements of the same tag. If the desired control is inside a known form or section, locate that parent first and search from it. This limits the search to descendants of that element.

from selenium.webdriver.common.by import By

form = driver.find_element(By.TAG_NAME, "form")
email_input = form.find_element(By.TAG_NAME, "input")

If there are multiple forms or inputs within the form, this is still too broad. Identify the parent more precisely, or use a stable attribute on the intended control. For example, if a predictable unique ID exists, Selenium recommends using it to identify a particular element.

Choose between tag name and another locator

Need Good starting point Why
Collect every link or input Tag name with the plural finder The element type defines the collection.
Find one element with a stable, unique ID ID locator A tag such as input often occurs many times.
Find an element in a known region Locate the parent, then search within it Restricts matching to that parent’s descendants.
Find a specific element by its class, text, or another attribute A locator expressing that identifying property Tag name alone does not match those properties.

Use tag-name lookup when the tag is the target or when you need a collection by element type. For a specific control, prefer an identifying property that is unique and predictable, when available.

Wait for elements that appear later

A page may render or update elements after navigation. If a lookup runs before the target exists, a singular lookup can fail. Use an explicit wait when the page behavior calls for waiting, and wait for the condition your next action needs.

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

link = WebDriverWait(driver, 10).until(
    EC.presence_of_element_located((By.TAG_NAME, "a"))
)

This waits for an a element to be present in the DOM. Presence does not establish that a particular link is the intended one or that it is ready for interaction. If there are several anchors, make the locator more specific; if the next step requires visibility or clickability, wait for that condition instead.

Common errors and fixes

Symptom Likely cause Fix
NoSuchElementException (Java) or NoSuchElementException (Python) No matching element is present in the current search context when the singular lookup runs. Confirm the tag and search context; wait for dynamic content when appropriate; check whether the element is inside a frame.
The lookup returns the wrong link or input The tag appears multiple times, and a tag-only locator does not distinguish them. Use a unique, predictable ID or another identifying attribute, or search from a more specific parent.
The plural lookup produces no results No matching descendants were found in the current context at lookup time. Check the tag, timing, parent context, and frame. Handle an empty collection before indexing or iterating over an assumed result.
Python reports a missing or incorrect locator argument The locator was called with the wrong API shape or tag spelling. Use driver.find_element(By.TAG_NAME, "input"); pass the tag without angle brackets.
Element lookup fails although the page visibly contains it The element may be in a different search context, such as an iframe, or the page may not have finished rendering it. Switch to the relevant frame before searching, or wait for the appropriate condition. Return to the default content when finished with the frame.

Performance, reliability, and cost

Tag-name lookup is straightforward, but broad matches make a test harder to maintain because page changes can alter which element is returned or how many are found. Scope searches and choose a locator that reflects the element’s intended identity. Use plural lookup for collections and handle the empty case; use an explicit wait only when the page’s behavior requires it.

These examples use Selenium WebDriver to control a browser. Browser setup and execution have their own runtime and infrastructure costs; this locator API does not define a service price. If your task is to capture page images rather than interact with elements in a browser test, a screenshot API can avoid managing browser setup for that capture.

Or skip the browser setup

For a screenshot rather than an interactive Selenium test, ScreenshotNeo is a website screenshot API and MCP server for developers. One GET request can return a PNG, JPEG, WebP, or PDF. Its capture process accepts cookie or consent banners like a visitor and removes more than 60 known consent platforms, newsletter popups, and chat widgets; each step can be turned off. Bot checks and CAPTCHAs, blank pages, timeouts, failed loads, and cache hits cost nothing, and response headers report the page verdict and billing status. Its MCP server provides take_screenshot, get_page_info, and capture_pdf tools for AI agents.

See the ScreenshotNeo API documentation. This cURL example saves a WebP screenshot:

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

Python:

import requests

r = requests.get(
    "https://api.screenshotneo.com/v1/shot",
    params={"access_key": "YOUR_API_KEY", "url": "https://stripe.com"},
    timeout=90,
)
open("shot.webp", "wb").write(r.content)

Node.js:

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 image = Buffer.from(await res.arrayBuffer());
await import('node:fs/promises').then(fs => fs.writeFile('shot.webp', image));

The free plan includes 1,000 screenshots per month with no card. Paid plans start at $5 for 3,000 screenshots; yearly billing gives two months free, and every feature is available on every plan. Sign up for 1,000 free screenshots a month, with no card.

FAQ

Do I include angle brackets in the tag name?

No. Pass "a" or "input", not "<a>" or "<input>".

Does tag-name lookup find an element by its text?

No. It matches the HTML tag. Choose a locator that represents the identifying property you need.

Use the plural finder with tag a, such as driver.find_elements(By.TAG_NAME, "a") in Python.