Finding web elements
One of the most fundamental aspects of using Selenium is obtaining element references to work with. Selenium offers a number of built-in locator strategies to uniquely identify an element. There are many ways to use the locators in very advanced scenarios. For the purposes of this documentation, use the Selenium locator test page.
First matching element
Many locators will match multiple elements on the page. The singular find element method will return a reference to the first element found within a given context.
Evaluating entire DOM
When the find element method is called on the driver instance, it
returns a reference to the first element in the DOM that matches with the provided locator.
This value can be stored and used for future element actions. On the Selenium locator test page, there are
two elements with the class name information, so this method returns the first text input.
driver.get(LOCATORS_PAGE);
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
# rubocop:disable RSpec/Output
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
# rubocop:enable RSpec/Output
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))
}
}
Evaluating a subset of the DOM
Rather than finding a unique locator in the entire DOM, it is often useful to narrow the search to the scope of another located element.
One solution is to locate an ancestor of the desired element, then call find element on that object:
driver.get(LOCATORS_PAGE);
WebElement form = driver.findElement(By.tagName("form"));
WebElement input = form.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);
}
}
# <ul id="fruits">
# <li class="bananas">…
# <li class="apples">…/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 form = driver.FindElement(By.TagName("form"));
IWebElement input = form.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);
}
}
}
it 'uses an optimized locator' do
driver.find_element(css: '#fruits .tomatoes')/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
# rubocop:disable RSpec/Output
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
# rubocop:enable RSpec/Output
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 form = await driver.findElement(By.tagName('form'));
const input = await form.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 form = driver.findElement(By.tagName("form"))
val input = form.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))
}
}
Java and C#WebDriver, WebElement and ShadowRoot classes all implement a SearchContext interface, which is
considered a role-based interface. Role-based interfaces allow you to determine whether a particular
driver implementation supports a given feature. These interfaces are clearly defined and try
to adhere to having only a single role of responsibility.
Evaluating the Shadow DOM
The Shadow DOM is an encapsulated DOM tree hidden inside an element. With the release of v96 in Chromium Browsers, Selenium can now allow you to access this tree with easy-to-use shadow root methods. NOTE: These methods require Selenium 4.0 or greater.
WebElement shadowHost = driver.findElement(By.cssSelector("#shadow_host"));
SearchContext shadowRoot = shadowHost.getShadowRoot();
WebElement shadowContent = shadowRoot.findElement(By.cssSelector("#shadow_content")); plants = driver.find_elements(By.TAG_NAME, 'li')
def test_evaluating_shadow_dom():/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()
var shadowHost = _driver.FindElement(By.CssSelector("#shadow_host"));
var shadowRoot = shadowHost.GetShadowRoot();
var shadowContent = shadowRoot.FindElement(By.CssSelector("#shadow_content"));shadow_host = @driver.find_element(css: '#shadow_host')
shadow_root = shadow_host.shadow_root
shadow_content = shadow_root.find_element(css: '#shadow_content')Optimized locator
A nested lookup might not be the most effective location strategy since it requires two separate commands to be issued to the browser.
To improve the performance slightly, we can use either CSS or XPath to find this element in a single command. See the Locator strategy suggestions in our Encouraged test practices section.
For this example, we’ll use a CSS selector:
driver.get(LOCATORS_PAGE);
WebElement input = driver.findElement(By.cssSelector("form .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);
}
}
def test_basic_finders(driver):
vegetable = driver.find_element(By.CLASS_NAME, 'tomatoes')/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 input = driver.FindElement(By.CssSelector("form .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);
}
}
}
# rubocop:disable RSpec/Output/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
# rubocop:disable RSpec/Output
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
# rubocop:enable RSpec/Output
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 input = await driver.findElement(By.css('form .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 input = driver.findElement(By.cssSelector("form .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))
}
}
All matching elements
There are several use cases for needing to get references to all elements that match a locator, rather than just the first one. The plural find elements methods return a collection of element references. If there are no matches, an empty list is returned. In this case, references to all input elements will be returned in a collection.
driver.get(LOCATORS_PAGE);
List<WebElement> inputs = driver.findElements(By.tagName("input"));/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);
}
}
fruit = fruits.find_element(By.CLASS_NAME, 'tomatoes')
/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;
var inputs = driver.FindElements(By.TagName("input"));/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);
}
}
}
it 'finds element from element' do
element = driver.find_element(:tag_name, 'div')/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
# rubocop:disable RSpec/Output
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
# rubocop:enable RSpec/Output
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 inputs = await driver.findElements(By.tagName('input'));/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 inputs = driver.findElements(By.tagName("input"))/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))
}
}
Get element
Often you get a collection of elements but want to work with a specific element, which means you need to iterate over the collection and identify the one you want.
List<WebElement> elements = driver.findElements(By.tagName("p"));
for (WebElement element : elements) {
System.out.println("Paragraph text:" + element.getText());
}/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);
}
}
assert shadow_host.is_displayed()
assert shadow_content.is_displayed()/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()
var elements = driver.FindElements(By.TagName("p"));
foreach (var element in elements)
{
System.Console.WriteLine("Paragraph text:" + element.Text);
}/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(css: '[name="q"]').send_keys('webElement')
driver.switch_to.active_element.attribute('title')
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
# rubocop:disable RSpec/Output
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
# rubocop:enable RSpec/Output
it 'find active element' do
driver.find_element(css: '[name="q"]').send_keys('webElement')
driver.switch_to.active_element.attribute('title')
end
end
end
const elements = await driver.findElements(By.tagName('p'));
for (const element of elements) {
console.log('Paragraph text:' + await element.getText());
}/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();
});
});
val elements = driver.findElements(By.tagName("p"))
for (element in elements) {
println("Paragraph text:" + element.text)
}/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))
}
}
Find Elements From Element
It is used to find the list of matching child WebElements within the context of parent element. To achieve this, the parent WebElement is chained with ‘findElements’ to access child elements
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"));
}/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);
}
}
elements = driver.find_elements(By.TAG_NAME, 'p')
for element in elements:
print(element.text)/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()
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"));
}/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);
}
}
}
/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
# rubocop:disable RSpec/Output
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
# rubocop:enable RSpec/Output
it 'find active element' do
driver.find_element(css: '[name="q"]').send_keys('webElement')
driver.switch_to.active_element.attribute('title')
end
end
end
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'));
}/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();
});
});
val form = driver.findElement(By.tagName("form"))
val elements = form.findElements(By.tagName("input"))
for (e in elements) {
println(e.getAttribute("value"))
}/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))
}
}
Get Active Element
It is used to track (or) find DOM element which has the focus in the current browsing context.
driver.findElement(By.cssSelector("#fname")).sendKeys("webElement");
String attr = driver.switchTo().activeElement().getAttribute("name");/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);
}
}
driver = webdriver.Chrome()
driver.get('https://www.example.com')/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.FindElement(By.CssSelector("#fname")).SendKeys("webElement");
string attr = driver.SwitchTo().ActiveElement().GetAttribute("name");/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);
}
}
}
/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
# rubocop:disable RSpec/Output
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
# rubocop:enable RSpec/Output
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.findElement(By.css('#fname')).sendKeys('webElement');
const attr = await driver.switchTo().activeElement().getAttribute('name');/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.findElement(By.cssSelector("#fname")).sendKeys("webElement")
val attr = driver.switchTo().activeElement().getAttribute("name")/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))
}
}




