Finding elements reliably
A locator copied out of the browser’s developer tools works today and breaks the first time a
designer moves a div. Tests then fail for reasons that have nothing to do with the behaviour
they were written to check, and the suite stops being trusted.
Recommended approach
Prefer locators that describe what an element is over locators that describe where it happens to sit in the document, roughly in this order:
- id, when the page has stable, unique ids. This is the fastest and most readable choice.
- name, for form fields, which tend to keep their names because the server depends on them.
- CSS selector, for everything else. A short selector anchored on an id, a data attribute, or a meaningful class is both fast and expressive.
- Relative locators, when the target has no stable attributes of its own but a nearby element does: find the input below a given label, or the button to the right of a field.
Avoid absolute XPath (/html/body/div[3]/...). It encodes the entire structure of the page, so
any change above the element breaks it, and it is slow in some browsers. XPath itself is fine
when you need it, for example to match on text content, but keep the expression short and
anchored.
If the application does not expose stable attributes, ask for them. A data-test attribute
costs the developers nothing and removes an entire class of failures.
Locate the first matching element:
WebElement firstInput = driver.findElement(By.className("information"));
/examples/java/src/test/java/dev/selenium/elements/FindersTest.java
package dev.selenium.elements;
import dev.selenium.BaseTest;
import org.junit.jupiter.api.Test;
import org.openqa.selenium.By;
import org.openqa.selenium.WebElement;
import java.util.List;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
public class FindersTest extends BaseTest {
private static final String LOCATORS_PAGE =
"https://www.selenium.dev/selenium/web/locators_tests/locators.html";
@Test
public void findsFirstMatchingElement() {
startChromeDriver();
driver.get(LOCATORS_PAGE);
WebElement firstInput = driver.findElement(By.className("information"));
assertEquals("fname", firstInput.getAttribute("id"));
}
@Test
public void findsElementWithinASubsetOfTheDom() {
startChromeDriver();
driver.get(LOCATORS_PAGE);
WebElement form = driver.findElement(By.tagName("form"));
WebElement input = form.findElement(By.className("information"));
assertEquals("fname", input.getAttribute("id"));
}
@Test
public void usesAnOptimizedLocator() {
startChromeDriver();
driver.get(LOCATORS_PAGE);
WebElement input = driver.findElement(By.cssSelector("form .information"));
assertEquals("fname", input.getAttribute("id"));
}
@Test
public void findsAllMatchingElements() {
startChromeDriver();
driver.get(LOCATORS_PAGE);
List<WebElement> inputs = driver.findElements(By.tagName("input"));
assertTrue(inputs.size() > 1);
}
@Test
public void getsElementFromACollection() {
startChromeDriver();
driver.get(LOCATORS_PAGE);
List<WebElement> elements = driver.findElements(By.tagName("p"));
for (WebElement element : elements) {
System.out.println("Paragraph text:" + element.getText());
}
assertTrue(elements.size() > 0);
}
@Test
public void findsElementsFromElement() {
startChromeDriver();
driver.get(LOCATORS_PAGE);
WebElement form = driver.findElement(By.tagName("form"));
List<WebElement> elements = form.findElements(By.tagName("input"));
for (WebElement e : elements) {
System.out.println(e.getAttribute("value"));
}
assertTrue(elements.size() > 0);
}
@Test
public void getsActiveElement() {
startChromeDriver();
driver.get(LOCATORS_PAGE);
driver.findElement(By.cssSelector("#fname")).sendKeys("webElement");
String attr = driver.switchTo().activeElement().getAttribute("name");
assertEquals("fname", attr);
}
}
# same examples are shown for the other language bindings:
#/examples/python/tests/elements/test_finders.py
import pytest
from selenium import webdriver
from selenium.webdriver.common.by import By
# The tests below marked as skipped mirror the HTML snippet shown at the top of the
# "Finding web elements" documentation and are illustrative only, matching how the
# same examples are shown for the other language bindings:
#
# <ol id="vegetables">
# <li class="potatoes">…
# <li class="onions">…
# <li class="tomatoes"><span>Tomato is a Vegetable</span>…
# </ol>
# <ul id="fruits">
# <li class="bananas">…
# <li class="apples">…
# <li class="tomatoes"><span>Tomato is a Fruit</span>…
# </ul>
@pytest.mark.skip(reason="illustrative example, not an executable test")
def test_basic_finders(driver):
vegetable = driver.find_element(By.CLASS_NAME, 'tomatoes')
@pytest.mark.skip(reason="illustrative example, not an executable test")
def test_subset_of_dom(driver):
fruits = driver.find_element(By.ID, 'fruits')
fruit = fruits.find_element(By.CLASS_NAME, 'tomatoes')
@pytest.mark.skip(reason="illustrative example, not an executable test")
def test_optimized_locator(driver):
fruit = driver.find_element(By.CSS_SELECTOR, '#fruits .tomatoes')
@pytest.mark.skip(reason="illustrative example, not an executable test")
def test_all_matching_elements(driver):
plants = driver.find_elements(By.TAG_NAME, 'li')
def test_evaluating_shadow_dom():
driver = webdriver.Chrome()
driver.implicitly_wait(5)
driver.get('https://www.selenium.dev/selenium/web/shadowRootPage.html')
shadow_host = driver.find_element(By.TAG_NAME, 'custom-checkbox-element')
shadow_root = shadow_host.shadow_root
assert shadow_root
shadow_content = shadow_root.find_element(By.CSS_SELECTOR, 'input[type=checkbox]')
assert shadow_host.is_displayed()
assert shadow_content.is_displayed()
driver.quit()
def test_get_element():
driver = webdriver.Chrome()
driver.get('https://www.example.com')
elements = driver.find_elements(By.TAG_NAME, 'p')
for element in elements:
print(element.text)
assert len(elements) > 0
driver.quit()
def test_find_elements_from_element():
driver = webdriver.Chrome()
driver.get('https://www.example.com')
element = driver.find_element(By.TAG_NAME, 'div')
elements = element.find_elements(By.TAG_NAME, 'p')
for e in elements:
print(e.text)
assert len(elements) > 0
driver.quit()
def test_get_active_element():
driver = webdriver.Chrome()
driver.get('https://www.selenium.dev/selenium/web/web-form.html')
driver.find_element(By.CSS_SELECTOR, '[name="my-text"]').send_keys('webElement')
attr = driver.switch_to.active_element.get_attribute('name')
assert attr == 'my-text'
driver.quit()
driver.Url = LocatorsPage;
IWebElement firstInput = driver.FindElement(By.ClassName("information"));/examples/dotnet/SeleniumDocs/Elements/FindersTest.cs
using Microsoft.VisualStudio.TestTools.UnitTesting;
using OpenQA.Selenium;
namespace SeleniumDocs.Elements
{
[TestClass]
public class FindersTest : BaseTest
{
private const string LocatorsPage = "https://www.selenium.dev/selenium/web/locators_tests/locators.html";
[TestMethod]
public void FindsFirstMatchingElement()
{
StartDriver();
driver.Url = LocatorsPage;
IWebElement firstInput = driver.FindElement(By.ClassName("information"));
Assert.AreEqual("fname", firstInput.GetAttribute("id"));
}
[TestMethod]
public void FindsElementWithinASubsetOfTheDom()
{
StartDriver();
driver.Url = LocatorsPage;
IWebElement form = driver.FindElement(By.TagName("form"));
IWebElement input = form.FindElement(By.ClassName("information"));
Assert.AreEqual("fname", input.GetAttribute("id"));
}
[TestMethod]
public void UsesAnOptimizedLocator()
{
StartDriver();
driver.Url = LocatorsPage;
IWebElement input = driver.FindElement(By.CssSelector("form .information"));
Assert.AreEqual("fname", input.GetAttribute("id"));
}
[TestMethod]
public void FindsAllMatchingElements()
{
StartDriver();
driver.Url = LocatorsPage;
var inputs = driver.FindElements(By.TagName("input"));
Assert.IsTrue(inputs.Count > 1);
}
[TestMethod]
public void GetsElementFromACollection()
{
StartDriver();
driver.Url = LocatorsPage;
var elements = driver.FindElements(By.TagName("p"));
foreach (var element in elements)
{
System.Console.WriteLine("Paragraph text:" + element.Text);
}
Assert.IsTrue(elements.Count > 0);
}
[TestMethod]
public void FindsElementsFromElement()
{
StartDriver();
driver.Url = LocatorsPage;
IWebElement form = driver.FindElement(By.TagName("form"));
var elements = form.FindElements(By.TagName("input"));
foreach (var e in elements)
{
System.Console.WriteLine(e.GetAttribute("value"));
}
Assert.IsTrue(elements.Count > 0);
}
[TestMethod]
public void GetsActiveElement()
{
StartDriver();
driver.Url = LocatorsPage;
driver.FindElement(By.CssSelector("#fname")).SendKeys("webElement");
string attr = driver.SwitchTo().ActiveElement().GetAttribute("name");
Assert.AreEqual("fname", attr);
}
}
}
driver.find_element(class: 'tomatoes')
end/examples/ruby/spec/elements/finders_spec.rb
# frozen_string_literal: true
require 'spec_helper'
RSpec.describe 'Element Finders' do
let(:driver) { start_session }
context 'without executing finders', skip: 'these are just examples, not actual tests' do
it 'finds the first matching element' do
driver.find_element(class: 'tomatoes')
end
it 'uses a subset of the dom to find an element' do
fruits = driver.find_element(id: 'fruits')
fruits.find_element(class: 'tomatoes')
end
it 'uses an optimized locator' do
driver.find_element(css: '#fruits .tomatoes')
end
it 'finds all matching elements' do
driver.find_elements(tag_name: 'li')
end
it 'gets an element from a collection' do
elements = driver.find_elements(:tag_name, 'p')
elements.each { |e| puts e.text }
end
it 'finds element from element' do
element = driver.find_element(:tag_name, 'div')
elements = element.find_elements(:tag_name, 'p')
elements.each { |e| puts e.text }
end
it 'find active element' do
driver.find_element(css: '[name="q"]').send_keys('webElement')
driver.switch_to.active_element.attribute('title')
end
end
end
await driver.get(LOCATORS_PAGE);
const firstInput = await driver.findElement(By.className('information'));/examples/javascript/test/elements/finders.spec.js
const {Builder, By} = require('selenium-webdriver');
const assert = require('assert');
const LOCATORS_PAGE = 'https://www.selenium.dev/selenium/web/locators_tests/locators.html';
describe('Finders', function () {
it('finds the first matching element', async function () {
let driver = await new Builder().forBrowser('chrome').build();
await driver.get(LOCATORS_PAGE);
const firstInput = await driver.findElement(By.className('information'));
assert.equal(await firstInput.getAttribute('id'), 'fname');
await driver.quit();
});
it('finds an element within a subset of the DOM', async function () {
let driver = await new Builder().forBrowser('chrome').build();
await driver.get(LOCATORS_PAGE);
const form = await driver.findElement(By.tagName('form'));
const input = await form.findElement(By.className('information'));
assert.equal(await input.getAttribute('id'), 'fname');
await driver.quit();
});
it('uses an optimized locator', async function () {
let driver = await new Builder().forBrowser('chrome').build();
await driver.get(LOCATORS_PAGE);
const input = await driver.findElement(By.css('form .information'));
assert.equal(await input.getAttribute('id'), 'fname');
await driver.quit();
});
it('finds all matching elements', async function () {
let driver = await new Builder().forBrowser('chrome').build();
await driver.get(LOCATORS_PAGE);
const inputs = await driver.findElements(By.tagName('input'));
assert.ok(inputs.length > 1);
await driver.quit();
});
it('gets an element from a collection', async function () {
let driver = await new Builder().forBrowser('chrome').build();
await driver.get(LOCATORS_PAGE);
const elements = await driver.findElements(By.tagName('p'));
for (const element of elements) {
console.log('Paragraph text:' + await element.getText());
}
assert.ok(elements.length > 0);
await driver.quit();
});
it('finds elements from an element', async function () {
let driver = await new Builder().forBrowser('chrome').build();
await driver.get(LOCATORS_PAGE);
const form = await driver.findElement(By.css('form'));
const elements = await form.findElements(By.css('input'));
for (const e of elements) {
console.log(await e.getAttribute('value'));
}
assert.ok(elements.length > 0);
await driver.quit();
});
it('gets the active element', async function () {
let driver = await new Builder().forBrowser('chrome').build();
await driver.get(LOCATORS_PAGE);
await driver.findElement(By.css('#fname')).sendKeys('webElement');
const attr = await driver.switchTo().activeElement().getAttribute('name');
assert.equal(attr, 'fname');
await driver.quit();
});
});
driver.get(locatorsPage)
val firstInput = driver.findElement(By.className("information"))/examples/kotlin/src/test/kotlin/dev/selenium/elements/FindersTest.kt
package dev.selenium.elements
import dev.selenium.BaseTest
import org.junit.jupiter.api.Assertions.assertEquals
import org.junit.jupiter.api.Assertions.assertTrue
import org.junit.jupiter.api.BeforeEach
import org.junit.jupiter.api.Test
import org.junit.jupiter.api.TestInstance
import org.openqa.selenium.By
import java.time.Duration
@TestInstance(TestInstance.Lifecycle.PER_CLASS)
class FindersTest : BaseTest() {
private val locatorsPage = "https://www.selenium.dev/selenium/web/locators_tests/locators.html"
@Test
fun findsFirstMatchingElement() {
driver.get(locatorsPage)
val firstInput = driver.findElement(By.className("information"))
assertEquals("fname", firstInput.getAttribute("id"))
}
@Test
fun findsElementWithinASubsetOfTheDom() {
driver.get(locatorsPage)
val form = driver.findElement(By.tagName("form"))
val input = form.findElement(By.className("information"))
assertEquals("fname", input.getAttribute("id"))
}
@Test
fun usesAnOptimizedLocator() {
driver.get(locatorsPage)
val input = driver.findElement(By.cssSelector("form .information"))
assertEquals("fname", input.getAttribute("id"))
}
@Test
fun findsAllMatchingElements() {
driver.get(locatorsPage)
val inputs = driver.findElements(By.tagName("input"))
assertTrue(inputs.size > 1)
}
@Test
fun getsElementFromACollection() {
driver.get(locatorsPage)
val elements = driver.findElements(By.tagName("p"))
for (element in elements) {
println("Paragraph text:" + element.text)
}
assertTrue(elements.isNotEmpty())
}
@Test
fun findsElementsFromElement() {
driver.get(locatorsPage)
val form = driver.findElement(By.tagName("form"))
val elements = form.findElements(By.tagName("input"))
for (e in elements) {
println(e.getAttribute("value"))
}
assertTrue(elements.isNotEmpty())
}
@Test
fun getsActiveElement() {
driver.get(locatorsPage)
driver.findElement(By.cssSelector("#fname")).sendKeys("webElement")
val attr = driver.switchTo().activeElement().getAttribute("name")
assertEquals("fname", attr)
}
@BeforeEach
fun configureImplicitWait() {
driver.manage().timeouts().implicitlyWait(Duration.ofMillis(500))
}
}
Locate by id, the preferred strategy when one is available:
}/examples/java/src/test/java/dev/selenium/elements/LocatorTest.java
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
public class LocatorTest {
private WebDriver driver;
@BeforeEach
public void setUp() {
// Initialize the driver before each test
driver = new ChromeDriver();
driver.get("https://www.selenium.dev/selenium/web/locators_tests/locators.html");
}
@AfterEach
public void tearDown() {
// Close the browser after each test
if (driver != null) {
driver.quit();
}
}
@Test
public void testClassName() {
WebElement element = driver.findElement(By.className("information"));
Assertions.assertNotNull(element);
Assertions.assertEquals("input", element.getTagName());
}
@Test
public void testCssSelector() {
WebElement element = driver.findElement(By.cssSelector("#fname"));
Assertions.assertNotNull(element);
Assertions.assertEquals("Jane", element.getAttribute("value"));
}
@Test
public void testId() {
WebElement element = driver.findElement(By.id("lname"));
Assertions.assertNotNull(element);
Assertions.assertEquals("Doe", element.getAttribute("value"));
}
@Test
public void testName() {
WebElement element = driver.findElement(By.name("newsletter"));
Assertions.assertNotNull(element);
Assertions.assertEquals("input", element.getTagName());
}
@Test
public void testLinkText() {
WebElement element = driver.findElement(By.linkText("Selenium Official Page"));
Assertions.assertNotNull(element);
Assertions.assertEquals("https://www.selenium.dev/", element.getAttribute("href"));
}
@Test
public void testPartialLinkText() {
WebElement element = driver.findElement(By.partialLinkText("Official Page"));
Assertions.assertNotNull(element);
Assertions.assertEquals("https://www.selenium.dev/", element.getAttribute("href"));
}
@Test
public void testTagName() {
WebElement element = driver.findElement(By.tagName("a"));
Assertions.assertNotNull(element);
Assertions.assertEquals("https://www.selenium.dev/", element.getAttribute("href"));
}
@Test
public void testXpath() {
WebElement element = driver.findElement(By.xpath("//input[@value='f']"));
Assertions.assertNotNull(element);
Assertions.assertEquals("radio", element.getAttribute("type"));
}
} element = driver.find_element(By.ID, "lname")/examples/python/tests/elements/test_locators.py
import pytest
from selenium import webdriver
from selenium.webdriver.common.by import By
def test_class_name():
driver = webdriver.Chrome()
driver.get("https://www.selenium.dev/selenium/web/locators_tests/locators.html")
element = driver.find_element(By.CLASS_NAME, "information")
assert element is not None
assert element.tag_name == "input"
driver.quit()
def test_css_selector(driver):
driver = webdriver.Chrome()
driver.get("https://www.selenium.dev/selenium/web/locators_tests/locators.html")
element = driver.find_element(By.CSS_SELECTOR, "#fname")
assert element is not None
assert element.get_attribute("value") == "Jane"
driver.quit()
def test_id(driver):
driver = webdriver.Chrome()
driver.get("https://www.selenium.dev/selenium/web/locators_tests/locators.html")
element = driver.find_element(By.ID, "lname")
assert element is not None
assert element.get_attribute("value") == "Doe"
driver.quit()
def test_name(driver):
driver = webdriver.Chrome()
driver.get("https://www.selenium.dev/selenium/web/locators_tests/locators.html")
element = driver.find_element(By.NAME, "newsletter")
assert element is not None
assert element.tag_name == "input"
driver.quit()
def test_link_text(driver):
driver = webdriver.Chrome()
driver.get("https://www.selenium.dev/selenium/web/locators_tests/locators.html")
element = driver.find_element(By.LINK_TEXT, "Selenium Official Page")
assert element is not None
assert element.get_attribute("href") == "https://www.selenium.dev/"
driver.quit()
def test_partial_link_text(driver):
driver = webdriver.Chrome()
driver.get("https://www.selenium.dev/selenium/web/locators_tests/locators.html")
element = driver.find_element(By.PARTIAL_LINK_TEXT, "Official Page")
assert element is not None
assert element.get_attribute("href") == "https://www.selenium.dev/"
driver.quit()
def test_tag_name(driver):
driver = webdriver.Chrome()
driver.get("https://www.selenium.dev/selenium/web/locators_tests/locators.html")
element = driver.find_element(By.TAG_NAME, "a")
assert element is not None
assert element.get_attribute("href") == "https://www.selenium.dev/"
driver.quit()
def test_xpath(driver):
driver = webdriver.Chrome()
driver.get("https://www.selenium.dev/selenium/web/locators_tests/locators.html")
element = driver.find_element(By.XPATH, "//input[@value='f']")
assert element is not None
assert element.get_attribute("type") == "radio"
driver.quit()
driver.find_element(id: 'lname')/examples/ruby/spec/elements/locators_spec.rb
# frozen_string_literal: true
require 'spec_helper'
RSpec.describe 'Element Locators', skip: 'These are reference following the documentation example' do
it 'finds element by class name' do
driver.find_element(class: 'information')
end
it 'finds element by css selector' do
driver.find_element(css: '#fname')
end
it 'finds element by id' do
driver.find_element(id: 'lname')
end
it 'find element by name' do
driver.find_element(name: 'newsletter')
end
it 'finds element by link text' do
driver.find_element(link_text: 'Selenium Official Page')
end
it 'finds element by partial link text' do
driver.find_element(partial_link_text: 'Official Page')
end
it 'finds element by tag name' do
driver.find_element(tag_name: 'a')
end
it 'finds element by xpath' do
driver.find_element(xpath: "//input[@value='f']")
end
context 'with relative locators' do
it 'finds element above' do
driver.find_element({relative: {tag_name: 'input', above: {id: 'password'}}})
end
it 'finds element below' do
driver.find_element({relative: {tag_name: 'input', below: {id: 'email'}}})
end
it 'finds element to the left' do
driver.find_element({relative: {tag_name: 'button', left: {id: 'submit'}}})
end
it 'finds element to the right' do
driver.find_element({relative: {tag_name: 'button', right: {id: 'cancel'}}})
end
it 'finds near element' do
driver.find_element({relative: {tag_name: 'input', near: {id: 'lbl-email'}}})
end
it 'chains relative locators' do
driver.find_element({relative: {tag_name: 'button', below: {id: 'email'}, right: {id: 'cancel'}}})
end
end
end
const element = await driver.findElement(By.id('lname'));/examples/javascript/test/elements/locators.spec.js
const {By, Builder} = require('selenium-webdriver');
const assert = require("assert");
describe('Element Locator Test', function () {
it('Check if element can be found by class name', async () => {
let driver = await new Builder().forBrowser('chrome').build();
await driver.get('https://www.selenium.dev/selenium/web/locators_tests/locators.html');
const element = await driver.findElement(By.className('information'));
const tag = await element.getTagName();
const id = await element.getAttribute("id");
const value = await element.getAttribute("value");
assert.equal(tag, "input");
assert.equal(id, "fname");
assert.equal(value, "Jane");
await driver.quit();
});
it('Check if element can be found by css selector', async function () {
let driver = await new Builder().forBrowser('chrome').build();
await driver.get('https://www.selenium.dev/selenium/web/locators_tests/locators.html');
const element = await driver.findElement(By.css('#fname'));
const tag = await element.getTagName();
const id = await element.getAttribute("id");
const value = await element.getAttribute("value");
assert.equal(tag, "input");
assert.equal(id, "fname");
assert.equal(value, "Jane");
await driver.quit();
});
it('Check if element can be found by id', async function () {
let driver = await new Builder().forBrowser('chrome').build();
await driver.get('https://www.selenium.dev/selenium/web/locators_tests/locators.html');
const element = await driver.findElement(By.id('lname'));
const tag = await element.getTagName();
const id = await element.getAttribute("id");
const value = await element.getAttribute("value");
assert.equal(tag, "input");
assert.equal(id, "lname");
assert.equal(value, "Doe");
await driver.quit();
});
it('Check if element can be found by name', async function () {
let driver = await new Builder().forBrowser('chrome').build();
await driver.get('https://www.selenium.dev/selenium/web/locators_tests/locators.html');
const element = await driver.findElement(By.name("newsletter"));
const tag = await element.getTagName();
const type = await element.getAttribute("type");
const value = await element.getAttribute("value");
assert.equal(tag, "input");
assert.equal(type, "checkbox");
assert.equal(value, "1");
await driver.quit();
});
it('Check if element can be found by link text', async function () {
let driver = await new Builder().forBrowser('chrome').build();
await driver.get('https://www.selenium.dev/selenium/web/locators_tests/locators.html');
const element = await driver.findElement(By.linkText("Selenium Official Page"));
const tag = await element.getTagName();
const href = await element.getAttribute("href");
assert.equal(tag, "a");
assert.equal(href, "https://www.selenium.dev/");
await driver.quit();
});
it('Check if element can be found by partial link text', async function () {
let driver = await new Builder().forBrowser('chrome').build();
await driver.get('https://www.selenium.dev/selenium/web/locators_tests/locators.html');
const element = await driver.findElement(By.partialLinkText("Official Page"));
const tag = await element.getTagName();
const href = await element.getAttribute("href");
assert.equal(tag, "a");
assert.equal(href, "https://www.selenium.dev/");
await driver.quit();
});
it('Check if element can be found by tag name', async function () {
let driver = await new Builder().forBrowser('chrome').build();
await driver.get('https://www.selenium.dev/selenium/web/locators_tests/locators.html');
const element = await driver.findElement(By.tagName("a"));
const tag = await element.getTagName();
const text = await element.getText();
assert.equal(tag, "a");
assert.equal(text, "Selenium Official Page");
await driver.quit();
});
it('Check if element can be found by xpath', async function () {
let driver = await new Builder().forBrowser('chrome').build();
await driver.get('https://www.selenium.dev/selenium/web/locators_tests/locators.html');
const element = await driver.findElement(By.xpath('//input[@value="f"]'));
const tag = await element.getTagName();
const type = await element.getAttribute("type");
const value = await element.getAttribute("value");
assert.equal(tag, "input");
assert.equal(type, "radio");
assert.equal(value, "f");
await driver.quit();
});
});
Locate relative to another element:
driver.find_element({relative: {tag_name: 'input', above: {id: 'password'}}})/examples/ruby/spec/elements/locators_spec.rb
# frozen_string_literal: true
require 'spec_helper'
RSpec.describe 'Element Locators', skip: 'These are reference following the documentation example' do
it 'finds element by class name' do
driver.find_element(class: 'information')
end
it 'finds element by css selector' do
driver.find_element(css: '#fname')
end
it 'finds element by id' do
driver.find_element(id: 'lname')
end
it 'find element by name' do
driver.find_element(name: 'newsletter')
end
it 'finds element by link text' do
driver.find_element(link_text: 'Selenium Official Page')
end
it 'finds element by partial link text' do
driver.find_element(partial_link_text: 'Official Page')
end
it 'finds element by tag name' do
driver.find_element(tag_name: 'a')
end
it 'finds element by xpath' do
driver.find_element(xpath: "//input[@value='f']")
end
context 'with relative locators' do
it 'finds element above' do
driver.find_element({relative: {tag_name: 'input', above: {id: 'password'}}})
end
it 'finds element below' do
driver.find_element({relative: {tag_name: 'input', below: {id: 'email'}}})
end
it 'finds element to the left' do
driver.find_element({relative: {tag_name: 'button', left: {id: 'submit'}}})
end
it 'finds element to the right' do
driver.find_element({relative: {tag_name: 'button', right: {id: 'cancel'}}})
end
it 'finds near element' do
driver.find_element({relative: {tag_name: 'input', near: {id: 'lbl-email'}}})
end
it 'chains relative locators' do
driver.find_element({relative: {tag_name: 'button', below: {id: 'email'}, right: {id: 'cancel'}}})
end
end
end
Common errors
- NoSuchElementException: nothing matched. Check the locator, check that you are in the right frame, and check that the element exists yet (see Waiting).
- InvalidSelectorException: the CSS or XPath expression is malformed, or an XPath expression returns something that is not an element.
- StaleElementReferenceException: you held on to an element across a page update. Locate it again rather than caching it.
- NoSuchShadowRootException: the element lives inside a shadow DOM; search from the shadow root instead of the document.
Reference
- Locator strategies: every strategy, including relative locators
- Finding elements: first match, all matches, nested searches, shadow DOM
- Tips on working with locators
- Page object models: keeping locators in one place



