大多数人的Selenium代码都涉及使用web元素.
1 - 查询网络元素
使用 Selenium 最基本的特点之一是获取可用于操作的元素引用。 Selenium 提供了许多内置的 定位策略,用于唯一标识元素。 在更复杂的场景中,可以用多种方式使用这些定位器。为了本篇文档的目的, 请使用 Selenium 定位器测试页面。
第一个匹配的元素
许多定位器会匹配页面上的多个元素。 单个的 find element 方法会返回在给定上下文中找到的第一个元素的引用。
在整个 DOM 中查找
当在 driver 实例上调用 find element 方法时,
它会返回 DOM 中与所提供定位器匹配的第一个元素的引用。
该引用可以被保存并用于后续的元素操作。
在 Selenium 定位器测试页面上,有两个 class 名称为 information 的元素,
因此此方法会返回第一个文本输入框。
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);
}
}
driver.get(LOCATORS_PAGE)
first_input = driver.find_element(By.CLASS_NAME, "information")/examples/python/tests/elements/test_finders.py
from selenium.webdriver.common.by import By
LOCATORS_PAGE = "https://www.selenium.dev/selenium/web/locators_tests/locators.html"
def test_first_matching_element(driver):
driver.get(LOCATORS_PAGE)
first_input = driver.find_element(By.CLASS_NAME, "information")
assert first_input.get_attribute("id") == "fname"
def test_subset_of_dom(driver):
driver.get(LOCATORS_PAGE)
form = driver.find_element(By.TAG_NAME, "form")
input_element = form.find_element(By.CLASS_NAME, "information")
assert input_element.get_attribute("id") == "fname"
def test_optimized_locator(driver):
driver.get(LOCATORS_PAGE)
input_element = driver.find_element(By.CSS_SELECTOR, "form .information")
assert input_element.get_attribute("id") == "fname"
def test_all_matching_elements(driver):
driver.get(LOCATORS_PAGE)
inputs = driver.find_elements(By.TAG_NAME, "input")
assert len(inputs) > 1
def test_evaluating_shadow_dom(driver):
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()
def test_get_element(driver):
driver.get(LOCATORS_PAGE)
elements = driver.find_elements(By.TAG_NAME, 'p')
for element in elements:
print(f"Paragraph text:{element.text}")
assert len(elements) > 0
def test_find_elements_from_element(driver):
driver.get(LOCATORS_PAGE)
form = driver.find_element(By.TAG_NAME, 'form')
elements = form.find_elements(By.TAG_NAME, 'input')
for element in elements:
print(element.get_attribute('value'))
assert len(elements) > 0
def test_get_active_element(driver):
driver.get(LOCATORS_PAGE)
driver.find_element(By.CSS_SELECTOR, '#fname').send_keys('webElement')
attr = driver.switch_to.active_element.get_attribute('name')
assert attr == 'fname'
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.navigate.to locators_page
first_input = driver.find_element(class: 'information')/examples/ruby/spec/elements/finders_spec.rb
# frozen_string_literal: true
require 'spec_helper'
RSpec.describe 'Element Finders' do
let(:driver) { start_session }
let(:locators_page) { 'https://www.selenium.dev/selenium/web/locators_tests/locators.html' }
it 'finds the first matching element' do
driver.navigate.to locators_page
first_input = driver.find_element(class: 'information')
expect(first_input.attribute('id')).to eq('fname')
end
it 'uses a subset of the dom to find an element' do
driver.navigate.to locators_page
form = driver.find_element(tag_name: 'form')
input_element = form.find_element(class: 'information')
expect(input_element.attribute('id')).to eq('fname')
end
it 'uses an optimized locator' do
driver.navigate.to locators_page
input_element = driver.find_element(css: 'form .information')
expect(input_element.attribute('id')).to eq('fname')
end
it 'finds all matching elements' do
driver.navigate.to locators_page
inputs = driver.find_elements(tag_name: 'input')
expect(inputs.size).to be > 1
end
# rubocop:disable RSpec/Output
it 'gets an element from a collection' do
driver.navigate.to locators_page
elements = driver.find_elements(tag_name: 'p')
elements.each { |e| puts "Paragraph text:#{e.text}" }
expect(elements).not_to be_empty
end
it 'finds element from element' do
driver.navigate.to locators_page
form = driver.find_element(tag_name: 'form')
elements = form.find_elements(tag_name: 'input')
elements.each { |e| puts e.attribute('value') }
expect(elements).not_to be_empty
end
# rubocop:enable RSpec/Output
it 'finds the active element' do
driver.navigate.to locators_page
driver.find_element(css: '#fname').send_keys('webElement')
attr = driver.switch_to.active_element.attribute('name')
expect(attr).to eq('fname')
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))
}
}
在 DOM 的子集内评估
与其在整个 DOM 中寻找唯一的定位器, 通常更有用的是将搜索范围缩小到另一个已定位元素的作用域内。
一种解决办法是先定位目标元素的祖先,
然后在该对象上调用 find element:
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);
}
}
driver.get(LOCATORS_PAGE)
form = driver.find_element(By.TAG_NAME, "form")
input_element = form.find_element(By.CLASS_NAME, "information")/examples/python/tests/elements/test_finders.py
from selenium.webdriver.common.by import By
LOCATORS_PAGE = "https://www.selenium.dev/selenium/web/locators_tests/locators.html"
def test_first_matching_element(driver):
driver.get(LOCATORS_PAGE)
first_input = driver.find_element(By.CLASS_NAME, "information")
assert first_input.get_attribute("id") == "fname"
def test_subset_of_dom(driver):
driver.get(LOCATORS_PAGE)
form = driver.find_element(By.TAG_NAME, "form")
input_element = form.find_element(By.CLASS_NAME, "information")
assert input_element.get_attribute("id") == "fname"
def test_optimized_locator(driver):
driver.get(LOCATORS_PAGE)
input_element = driver.find_element(By.CSS_SELECTOR, "form .information")
assert input_element.get_attribute("id") == "fname"
def test_all_matching_elements(driver):
driver.get(LOCATORS_PAGE)
inputs = driver.find_elements(By.TAG_NAME, "input")
assert len(inputs) > 1
def test_evaluating_shadow_dom(driver):
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()
def test_get_element(driver):
driver.get(LOCATORS_PAGE)
elements = driver.find_elements(By.TAG_NAME, 'p')
for element in elements:
print(f"Paragraph text:{element.text}")
assert len(elements) > 0
def test_find_elements_from_element(driver):
driver.get(LOCATORS_PAGE)
form = driver.find_element(By.TAG_NAME, 'form')
elements = form.find_elements(By.TAG_NAME, 'input')
for element in elements:
print(element.get_attribute('value'))
assert len(elements) > 0
def test_get_active_element(driver):
driver.get(LOCATORS_PAGE)
driver.find_element(By.CSS_SELECTOR, '#fname').send_keys('webElement')
attr = driver.switch_to.active_element.get_attribute('name')
assert attr == 'fname'
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);
}
}
}
driver.navigate.to locators_page
form = driver.find_element(tag_name: 'form')
input_element = form.find_element(class: 'information')/examples/ruby/spec/elements/finders_spec.rb
# frozen_string_literal: true
require 'spec_helper'
RSpec.describe 'Element Finders' do
let(:driver) { start_session }
let(:locators_page) { 'https://www.selenium.dev/selenium/web/locators_tests/locators.html' }
it 'finds the first matching element' do
driver.navigate.to locators_page
first_input = driver.find_element(class: 'information')
expect(first_input.attribute('id')).to eq('fname')
end
it 'uses a subset of the dom to find an element' do
driver.navigate.to locators_page
form = driver.find_element(tag_name: 'form')
input_element = form.find_element(class: 'information')
expect(input_element.attribute('id')).to eq('fname')
end
it 'uses an optimized locator' do
driver.navigate.to locators_page
input_element = driver.find_element(css: 'form .information')
expect(input_element.attribute('id')).to eq('fname')
end
it 'finds all matching elements' do
driver.navigate.to locators_page
inputs = driver.find_elements(tag_name: 'input')
expect(inputs.size).to be > 1
end
# rubocop:disable RSpec/Output
it 'gets an element from a collection' do
driver.navigate.to locators_page
elements = driver.find_elements(tag_name: 'p')
elements.each { |e| puts "Paragraph text:#{e.text}" }
expect(elements).not_to be_empty
end
it 'finds element from element' do
driver.navigate.to locators_page
form = driver.find_element(tag_name: 'form')
elements = form.find_elements(tag_name: 'input')
elements.each { |e| puts e.attribute('value') }
expect(elements).not_to be_empty
end
# rubocop:enable RSpec/Output
it 'finds the active element' do
driver.navigate.to locators_page
driver.find_element(css: '#fname').send_keys('webElement')
attr = driver.switch_to.active_element.attribute('name')
expect(attr).to eq('fname')
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 和 C#WebDriver、WebElement 和 ShadowRoot 类都实现了 SearchContext 接口,
该接口被视为一种 基于角色的接口。基于角色的接口可以让你判断特定的驱动实现是否支持某项功能。
这些接口定义清晰,并尽量遵循单一职责原则。
评估 Shadow DOM
Shadow DOM 是隐藏在元素内部的封装 DOM 树。
自 Chromium 浏览器在 v96 发布后,Selenium 已支持通过易用的 shadow root 方法访问该树。注意:这些方法需要 Selenium 4.0 或更高版本。
WebElement shadowHost = driver.findElement(By.cssSelector("#shadow_host"));
SearchContext shadowRoot = shadowHost.getShadowRoot();
WebElement shadowContent = shadowRoot.findElement(By.cssSelector("#shadow_content")); 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]')/examples/python/tests/elements/test_finders.py
from selenium.webdriver.common.by import By
LOCATORS_PAGE = "https://www.selenium.dev/selenium/web/locators_tests/locators.html"
def test_first_matching_element(driver):
driver.get(LOCATORS_PAGE)
first_input = driver.find_element(By.CLASS_NAME, "information")
assert first_input.get_attribute("id") == "fname"
def test_subset_of_dom(driver):
driver.get(LOCATORS_PAGE)
form = driver.find_element(By.TAG_NAME, "form")
input_element = form.find_element(By.CLASS_NAME, "information")
assert input_element.get_attribute("id") == "fname"
def test_optimized_locator(driver):
driver.get(LOCATORS_PAGE)
input_element = driver.find_element(By.CSS_SELECTOR, "form .information")
assert input_element.get_attribute("id") == "fname"
def test_all_matching_elements(driver):
driver.get(LOCATORS_PAGE)
inputs = driver.find_elements(By.TAG_NAME, "input")
assert len(inputs) > 1
def test_evaluating_shadow_dom(driver):
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()
def test_get_element(driver):
driver.get(LOCATORS_PAGE)
elements = driver.find_elements(By.TAG_NAME, 'p')
for element in elements:
print(f"Paragraph text:{element.text}")
assert len(elements) > 0
def test_find_elements_from_element(driver):
driver.get(LOCATORS_PAGE)
form = driver.find_element(By.TAG_NAME, 'form')
elements = form.find_elements(By.TAG_NAME, 'input')
for element in elements:
print(element.get_attribute('value'))
assert len(elements) > 0
def test_get_active_element(driver):
driver.get(LOCATORS_PAGE)
driver.find_element(By.CSS_SELECTOR, '#fname').send_keys('webElement')
attr = driver.switch_to.active_element.get_attribute('name')
assert attr == 'fname'
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')优化后的定位器
嵌套查找可能不是最有效的定位策略, 因为它需要向浏览器发送两次独立的命令。
为略微提升性能,我们可以使用 CSS 或 XPath,在一次命令中定位到该元素。 请参阅本节中关于定位策略建议的说明 以及推荐的测试实践。
在本例中,我们将使用 CSS 选择器:
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);
}
}
driver.get(LOCATORS_PAGE)
input_element = driver.find_element(By.CSS_SELECTOR, "form .information")/examples/python/tests/elements/test_finders.py
from selenium.webdriver.common.by import By
LOCATORS_PAGE = "https://www.selenium.dev/selenium/web/locators_tests/locators.html"
def test_first_matching_element(driver):
driver.get(LOCATORS_PAGE)
first_input = driver.find_element(By.CLASS_NAME, "information")
assert first_input.get_attribute("id") == "fname"
def test_subset_of_dom(driver):
driver.get(LOCATORS_PAGE)
form = driver.find_element(By.TAG_NAME, "form")
input_element = form.find_element(By.CLASS_NAME, "information")
assert input_element.get_attribute("id") == "fname"
def test_optimized_locator(driver):
driver.get(LOCATORS_PAGE)
input_element = driver.find_element(By.CSS_SELECTOR, "form .information")
assert input_element.get_attribute("id") == "fname"
def test_all_matching_elements(driver):
driver.get(LOCATORS_PAGE)
inputs = driver.find_elements(By.TAG_NAME, "input")
assert len(inputs) > 1
def test_evaluating_shadow_dom(driver):
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()
def test_get_element(driver):
driver.get(LOCATORS_PAGE)
elements = driver.find_elements(By.TAG_NAME, 'p')
for element in elements:
print(f"Paragraph text:{element.text}")
assert len(elements) > 0
def test_find_elements_from_element(driver):
driver.get(LOCATORS_PAGE)
form = driver.find_element(By.TAG_NAME, 'form')
elements = form.find_elements(By.TAG_NAME, 'input')
for element in elements:
print(element.get_attribute('value'))
assert len(elements) > 0
def test_get_active_element(driver):
driver.get(LOCATORS_PAGE)
driver.find_element(By.CSS_SELECTOR, '#fname').send_keys('webElement')
attr = driver.switch_to.active_element.get_attribute('name')
assert attr == 'fname'
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);
}
}
}
driver.navigate.to locators_page
input_element = driver.find_element(css: 'form .information')/examples/ruby/spec/elements/finders_spec.rb
# frozen_string_literal: true
require 'spec_helper'
RSpec.describe 'Element Finders' do
let(:driver) { start_session }
let(:locators_page) { 'https://www.selenium.dev/selenium/web/locators_tests/locators.html' }
it 'finds the first matching element' do
driver.navigate.to locators_page
first_input = driver.find_element(class: 'information')
expect(first_input.attribute('id')).to eq('fname')
end
it 'uses a subset of the dom to find an element' do
driver.navigate.to locators_page
form = driver.find_element(tag_name: 'form')
input_element = form.find_element(class: 'information')
expect(input_element.attribute('id')).to eq('fname')
end
it 'uses an optimized locator' do
driver.navigate.to locators_page
input_element = driver.find_element(css: 'form .information')
expect(input_element.attribute('id')).to eq('fname')
end
it 'finds all matching elements' do
driver.navigate.to locators_page
inputs = driver.find_elements(tag_name: 'input')
expect(inputs.size).to be > 1
end
# rubocop:disable RSpec/Output
it 'gets an element from a collection' do
driver.navigate.to locators_page
elements = driver.find_elements(tag_name: 'p')
elements.each { |e| puts "Paragraph text:#{e.text}" }
expect(elements).not_to be_empty
end
it 'finds element from element' do
driver.navigate.to locators_page
form = driver.find_element(tag_name: 'form')
elements = form.find_elements(tag_name: 'input')
elements.each { |e| puts e.attribute('value') }
expect(elements).not_to be_empty
end
# rubocop:enable RSpec/Output
it 'finds the active element' do
driver.navigate.to locators_page
driver.find_element(css: '#fname').send_keys('webElement')
attr = driver.switch_to.active_element.attribute('name')
expect(attr).to eq('fname')
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))
}
}
所有匹配的元素
在某些情况下,需要获取与定位器匹配的所有元素的引用,而不是仅获取第一个。
复数形式的 find elements 方法会返回一组元素引用。如果没有匹配项,则返回空列表。
在本例中,将返回所有 input 元素的引用集合。
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);
}
}
driver.get(LOCATORS_PAGE)
inputs = driver.find_elements(By.TAG_NAME, "input")/examples/python/tests/elements/test_finders.py
from selenium.webdriver.common.by import By
LOCATORS_PAGE = "https://www.selenium.dev/selenium/web/locators_tests/locators.html"
def test_first_matching_element(driver):
driver.get(LOCATORS_PAGE)
first_input = driver.find_element(By.CLASS_NAME, "information")
assert first_input.get_attribute("id") == "fname"
def test_subset_of_dom(driver):
driver.get(LOCATORS_PAGE)
form = driver.find_element(By.TAG_NAME, "form")
input_element = form.find_element(By.CLASS_NAME, "information")
assert input_element.get_attribute("id") == "fname"
def test_optimized_locator(driver):
driver.get(LOCATORS_PAGE)
input_element = driver.find_element(By.CSS_SELECTOR, "form .information")
assert input_element.get_attribute("id") == "fname"
def test_all_matching_elements(driver):
driver.get(LOCATORS_PAGE)
inputs = driver.find_elements(By.TAG_NAME, "input")
assert len(inputs) > 1
def test_evaluating_shadow_dom(driver):
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()
def test_get_element(driver):
driver.get(LOCATORS_PAGE)
elements = driver.find_elements(By.TAG_NAME, 'p')
for element in elements:
print(f"Paragraph text:{element.text}")
assert len(elements) > 0
def test_find_elements_from_element(driver):
driver.get(LOCATORS_PAGE)
form = driver.find_element(By.TAG_NAME, 'form')
elements = form.find_elements(By.TAG_NAME, 'input')
for element in elements:
print(element.get_attribute('value'))
assert len(elements) > 0
def test_get_active_element(driver):
driver.get(LOCATORS_PAGE)
driver.find_element(By.CSS_SELECTOR, '#fname').send_keys('webElement')
attr = driver.switch_to.active_element.get_attribute('name')
assert attr == 'fname'
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);
}
}
}
driver.navigate.to locators_page
inputs = driver.find_elements(tag_name: 'input')/examples/ruby/spec/elements/finders_spec.rb
# frozen_string_literal: true
require 'spec_helper'
RSpec.describe 'Element Finders' do
let(:driver) { start_session }
let(:locators_page) { 'https://www.selenium.dev/selenium/web/locators_tests/locators.html' }
it 'finds the first matching element' do
driver.navigate.to locators_page
first_input = driver.find_element(class: 'information')
expect(first_input.attribute('id')).to eq('fname')
end
it 'uses a subset of the dom to find an element' do
driver.navigate.to locators_page
form = driver.find_element(tag_name: 'form')
input_element = form.find_element(class: 'information')
expect(input_element.attribute('id')).to eq('fname')
end
it 'uses an optimized locator' do
driver.navigate.to locators_page
input_element = driver.find_element(css: 'form .information')
expect(input_element.attribute('id')).to eq('fname')
end
it 'finds all matching elements' do
driver.navigate.to locators_page
inputs = driver.find_elements(tag_name: 'input')
expect(inputs.size).to be > 1
end
# rubocop:disable RSpec/Output
it 'gets an element from a collection' do
driver.navigate.to locators_page
elements = driver.find_elements(tag_name: 'p')
elements.each { |e| puts "Paragraph text:#{e.text}" }
expect(elements).not_to be_empty
end
it 'finds element from element' do
driver.navigate.to locators_page
form = driver.find_element(tag_name: 'form')
elements = form.find_elements(tag_name: 'input')
elements.each { |e| puts e.attribute('value') }
expect(elements).not_to be_empty
end
# rubocop:enable RSpec/Output
it 'finds the active element' do
driver.navigate.to locators_page
driver.find_element(css: '#fname').send_keys('webElement')
attr = driver.switch_to.active_element.attribute('name')
expect(attr).to eq('fname')
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))
}
}
获取元素
有时你会得到一组元素,但想操作其中某个特定元素, 这意味着需要遍历该集合并找到目标元素。
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);
}
}
elements = driver.find_elements(By.TAG_NAME, 'p')
for element in elements:
print(f"Paragraph text:{element.text}")/examples/python/tests/elements/test_finders.py
from selenium.webdriver.common.by import By
LOCATORS_PAGE = "https://www.selenium.dev/selenium/web/locators_tests/locators.html"
def test_first_matching_element(driver):
driver.get(LOCATORS_PAGE)
first_input = driver.find_element(By.CLASS_NAME, "information")
assert first_input.get_attribute("id") == "fname"
def test_subset_of_dom(driver):
driver.get(LOCATORS_PAGE)
form = driver.find_element(By.TAG_NAME, "form")
input_element = form.find_element(By.CLASS_NAME, "information")
assert input_element.get_attribute("id") == "fname"
def test_optimized_locator(driver):
driver.get(LOCATORS_PAGE)
input_element = driver.find_element(By.CSS_SELECTOR, "form .information")
assert input_element.get_attribute("id") == "fname"
def test_all_matching_elements(driver):
driver.get(LOCATORS_PAGE)
inputs = driver.find_elements(By.TAG_NAME, "input")
assert len(inputs) > 1
def test_evaluating_shadow_dom(driver):
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()
def test_get_element(driver):
driver.get(LOCATORS_PAGE)
elements = driver.find_elements(By.TAG_NAME, 'p')
for element in elements:
print(f"Paragraph text:{element.text}")
assert len(elements) > 0
def test_find_elements_from_element(driver):
driver.get(LOCATORS_PAGE)
form = driver.find_element(By.TAG_NAME, 'form')
elements = form.find_elements(By.TAG_NAME, 'input')
for element in elements:
print(element.get_attribute('value'))
assert len(elements) > 0
def test_get_active_element(driver):
driver.get(LOCATORS_PAGE)
driver.find_element(By.CSS_SELECTOR, '#fname').send_keys('webElement')
attr = driver.switch_to.active_element.get_attribute('name')
assert attr == 'fname'
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.navigate.to locators_page
elements = driver.find_elements(tag_name: 'p')
elements.each { |e| puts "Paragraph text:#{e.text}" }/examples/ruby/spec/elements/finders_spec.rb
# frozen_string_literal: true
require 'spec_helper'
RSpec.describe 'Element Finders' do
let(:driver) { start_session }
let(:locators_page) { 'https://www.selenium.dev/selenium/web/locators_tests/locators.html' }
it 'finds the first matching element' do
driver.navigate.to locators_page
first_input = driver.find_element(class: 'information')
expect(first_input.attribute('id')).to eq('fname')
end
it 'uses a subset of the dom to find an element' do
driver.navigate.to locators_page
form = driver.find_element(tag_name: 'form')
input_element = form.find_element(class: 'information')
expect(input_element.attribute('id')).to eq('fname')
end
it 'uses an optimized locator' do
driver.navigate.to locators_page
input_element = driver.find_element(css: 'form .information')
expect(input_element.attribute('id')).to eq('fname')
end
it 'finds all matching elements' do
driver.navigate.to locators_page
inputs = driver.find_elements(tag_name: 'input')
expect(inputs.size).to be > 1
end
# rubocop:disable RSpec/Output
it 'gets an element from a collection' do
driver.navigate.to locators_page
elements = driver.find_elements(tag_name: 'p')
elements.each { |e| puts "Paragraph text:#{e.text}" }
expect(elements).not_to be_empty
end
it 'finds element from element' do
driver.navigate.to locators_page
form = driver.find_element(tag_name: 'form')
elements = form.find_elements(tag_name: 'input')
elements.each { |e| puts e.attribute('value') }
expect(elements).not_to be_empty
end
# rubocop:enable RSpec/Output
it 'finds the active element' do
driver.navigate.to locators_page
driver.find_element(css: '#fname').send_keys('webElement')
attr = driver.switch_to.active_element.attribute('name')
expect(attr).to eq('fname')
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))
}
}
从元素查找子元素
用于在父元素的上下文中查找匹配的子 WebElement 列表。
为此,可在父 WebElement 上链式调用 findElements 来访问子元素。
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);
}
}
form = driver.find_element(By.TAG_NAME, 'form')
elements = form.find_elements(By.TAG_NAME, 'input')
for element in elements:
print(element.get_attribute('value'))/examples/python/tests/elements/test_finders.py
from selenium.webdriver.common.by import By
LOCATORS_PAGE = "https://www.selenium.dev/selenium/web/locators_tests/locators.html"
def test_first_matching_element(driver):
driver.get(LOCATORS_PAGE)
first_input = driver.find_element(By.CLASS_NAME, "information")
assert first_input.get_attribute("id") == "fname"
def test_subset_of_dom(driver):
driver.get(LOCATORS_PAGE)
form = driver.find_element(By.TAG_NAME, "form")
input_element = form.find_element(By.CLASS_NAME, "information")
assert input_element.get_attribute("id") == "fname"
def test_optimized_locator(driver):
driver.get(LOCATORS_PAGE)
input_element = driver.find_element(By.CSS_SELECTOR, "form .information")
assert input_element.get_attribute("id") == "fname"
def test_all_matching_elements(driver):
driver.get(LOCATORS_PAGE)
inputs = driver.find_elements(By.TAG_NAME, "input")
assert len(inputs) > 1
def test_evaluating_shadow_dom(driver):
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()
def test_get_element(driver):
driver.get(LOCATORS_PAGE)
elements = driver.find_elements(By.TAG_NAME, 'p')
for element in elements:
print(f"Paragraph text:{element.text}")
assert len(elements) > 0
def test_find_elements_from_element(driver):
driver.get(LOCATORS_PAGE)
form = driver.find_element(By.TAG_NAME, 'form')
elements = form.find_elements(By.TAG_NAME, 'input')
for element in elements:
print(element.get_attribute('value'))
assert len(elements) > 0
def test_get_active_element(driver):
driver.get(LOCATORS_PAGE)
driver.find_element(By.CSS_SELECTOR, '#fname').send_keys('webElement')
attr = driver.switch_to.active_element.get_attribute('name')
assert attr == 'fname'
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);
}
}
}
driver.navigate.to locators_page
form = driver.find_element(tag_name: 'form')
elements = form.find_elements(tag_name: 'input')
elements.each { |e| puts e.attribute('value') }/examples/ruby/spec/elements/finders_spec.rb
# frozen_string_literal: true
require 'spec_helper'
RSpec.describe 'Element Finders' do
let(:driver) { start_session }
let(:locators_page) { 'https://www.selenium.dev/selenium/web/locators_tests/locators.html' }
it 'finds the first matching element' do
driver.navigate.to locators_page
first_input = driver.find_element(class: 'information')
expect(first_input.attribute('id')).to eq('fname')
end
it 'uses a subset of the dom to find an element' do
driver.navigate.to locators_page
form = driver.find_element(tag_name: 'form')
input_element = form.find_element(class: 'information')
expect(input_element.attribute('id')).to eq('fname')
end
it 'uses an optimized locator' do
driver.navigate.to locators_page
input_element = driver.find_element(css: 'form .information')
expect(input_element.attribute('id')).to eq('fname')
end
it 'finds all matching elements' do
driver.navigate.to locators_page
inputs = driver.find_elements(tag_name: 'input')
expect(inputs.size).to be > 1
end
# rubocop:disable RSpec/Output
it 'gets an element from a collection' do
driver.navigate.to locators_page
elements = driver.find_elements(tag_name: 'p')
elements.each { |e| puts "Paragraph text:#{e.text}" }
expect(elements).not_to be_empty
end
it 'finds element from element' do
driver.navigate.to locators_page
form = driver.find_element(tag_name: 'form')
elements = form.find_elements(tag_name: 'input')
elements.each { |e| puts e.attribute('value') }
expect(elements).not_to be_empty
end
# rubocop:enable RSpec/Output
it 'finds the active element' do
driver.navigate.to locators_page
driver.find_element(css: '#fname').send_keys('webElement')
attr = driver.switch_to.active_element.attribute('name')
expect(attr).to eq('fname')
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))
}
}
获取活动元素
用于跟踪或查找当前浏览上下文中具有焦点的 DOM 元素。
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.find_element(By.CSS_SELECTOR, '#fname').send_keys('webElement')
attr = driver.switch_to.active_element.get_attribute('name')/examples/python/tests/elements/test_finders.py
from selenium.webdriver.common.by import By
LOCATORS_PAGE = "https://www.selenium.dev/selenium/web/locators_tests/locators.html"
def test_first_matching_element(driver):
driver.get(LOCATORS_PAGE)
first_input = driver.find_element(By.CLASS_NAME, "information")
assert first_input.get_attribute("id") == "fname"
def test_subset_of_dom(driver):
driver.get(LOCATORS_PAGE)
form = driver.find_element(By.TAG_NAME, "form")
input_element = form.find_element(By.CLASS_NAME, "information")
assert input_element.get_attribute("id") == "fname"
def test_optimized_locator(driver):
driver.get(LOCATORS_PAGE)
input_element = driver.find_element(By.CSS_SELECTOR, "form .information")
assert input_element.get_attribute("id") == "fname"
def test_all_matching_elements(driver):
driver.get(LOCATORS_PAGE)
inputs = driver.find_elements(By.TAG_NAME, "input")
assert len(inputs) > 1
def test_evaluating_shadow_dom(driver):
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()
def test_get_element(driver):
driver.get(LOCATORS_PAGE)
elements = driver.find_elements(By.TAG_NAME, 'p')
for element in elements:
print(f"Paragraph text:{element.text}")
assert len(elements) > 0
def test_find_elements_from_element(driver):
driver.get(LOCATORS_PAGE)
form = driver.find_element(By.TAG_NAME, 'form')
elements = form.find_elements(By.TAG_NAME, 'input')
for element in elements:
print(element.get_attribute('value'))
assert len(elements) > 0
def test_get_active_element(driver):
driver.get(LOCATORS_PAGE)
driver.find_element(By.CSS_SELECTOR, '#fname').send_keys('webElement')
attr = driver.switch_to.active_element.get_attribute('name')
assert attr == 'fname'
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);
}
}
}
driver.navigate.to locators_page
driver.find_element(css: '#fname').send_keys('webElement')
attr = driver.switch_to.active_element.attribute('name')/examples/ruby/spec/elements/finders_spec.rb
# frozen_string_literal: true
require 'spec_helper'
RSpec.describe 'Element Finders' do
let(:driver) { start_session }
let(:locators_page) { 'https://www.selenium.dev/selenium/web/locators_tests/locators.html' }
it 'finds the first matching element' do
driver.navigate.to locators_page
first_input = driver.find_element(class: 'information')
expect(first_input.attribute('id')).to eq('fname')
end
it 'uses a subset of the dom to find an element' do
driver.navigate.to locators_page
form = driver.find_element(tag_name: 'form')
input_element = form.find_element(class: 'information')
expect(input_element.attribute('id')).to eq('fname')
end
it 'uses an optimized locator' do
driver.navigate.to locators_page
input_element = driver.find_element(css: 'form .information')
expect(input_element.attribute('id')).to eq('fname')
end
it 'finds all matching elements' do
driver.navigate.to locators_page
inputs = driver.find_elements(tag_name: 'input')
expect(inputs.size).to be > 1
end
# rubocop:disable RSpec/Output
it 'gets an element from a collection' do
driver.navigate.to locators_page
elements = driver.find_elements(tag_name: 'p')
elements.each { |e| puts "Paragraph text:#{e.text}" }
expect(elements).not_to be_empty
end
it 'finds element from element' do
driver.navigate.to locators_page
form = driver.find_element(tag_name: 'form')
elements = form.find_elements(tag_name: 'input')
elements.each { |e| puts e.attribute('value') }
expect(elements).not_to be_empty
end
# rubocop:enable RSpec/Output
it 'finds the active element' do
driver.navigate.to locators_page
driver.find_element(css: '#fname').send_keys('webElement')
attr = driver.switch_to.active_element.attribute('name')
expect(attr).to eq('fname')
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))
}
}
2 - Web元素交互
仅有五种基本命令可用于元素的操作:
附加验证
这些方法的设计目的是尽量模拟用户体验, 所以, 与 Actions接口 不同, 在指定制定操作之前, 会尝试执行两件事.
- 如果它确定元素在视口之外, 则会将元素滚动到视图中, 特别是将元素底部与视口底部对齐.
- 确保元素在执行操作之前是可交互的 .
这可能意味着滚动不成功,
或者该元素没有以其他方式显示.
确定某个元素是否显示在页面上太难了 无法直接在webdriver规范中定义, 因此Selenium发送一个带有JavaScript原子的执行命令, 检查是否有可能阻止该元素显示. 如果确定某个元素不在视口中, 不显示, 不可 键盘交互, 或不可 指针交互, 则返回一个元素不可交互 错误.
点击
元素点击命令 执行在 元素中央. 如果元素中央由于某些原因被 遮挡 , Selenium将返回一个 元素点击中断 错误.
driver.get("https://www.selenium.dev/selenium/web/inputs.html");
// Click on the element
WebElement checkInput = driver.findElement(By.name("checkbox_input"));
checkInput.click();/examples/java/src/test/java/dev/selenium/elements/InteractionTest.java
package dev.selenium.elements;
import org.junit.jupiter.api.Test;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import java.time.Duration;
import static org.junit.jupiter.api.Assertions.assertEquals;
public class InteractionTest {
@Test
public void interactWithElements() {
WebDriver driver = new ChromeDriver();
driver.manage().timeouts().implicitlyWait(Duration.ofMillis(500));
// Navigate to Url
driver.get("https://www.selenium.dev/selenium/web/inputs.html");
// Click on the element
WebElement checkInput = driver.findElement(By.name("checkbox_input"));
checkInput.click();
Boolean isChecked = checkInput.isSelected();
assertEquals(isChecked, false);
// SendKeys
// Clear field to empty it from any previous data
WebElement emailInput = driver.findElement(By.name("email_input"));
emailInput.clear();
// Enter Text
String email = "admin@localhost.dev";
emailInput.sendKeys(email);
// Verify
String data = emailInput.getAttribute("value");
assertEquals(data, email);
// Clear Element
// Clear field to empty it from any previous data
emailInput.clear();
data = emailInput.getAttribute("value");
assertEquals(data, "");
driver.quit();
}
} # Navigate to URL
driver.get("https://www.selenium.dev/selenium/web/inputs.html")
# Click on the checkbox
check_input = driver.find_element(By.NAME, "checkbox_input")
check_input.click()/examples/python/tests/elements/test_interaction.py
from selenium import webdriver
from selenium.webdriver.common.by import By
import pytest
def test_interactions():
# Initialize WebDriver
driver = webdriver.Chrome()
driver.implicitly_wait(0.5)
# Navigate to URL
driver.get("https://www.selenium.dev/selenium/web/inputs.html")
# Click on the checkbox
check_input = driver.find_element(By.NAME, "checkbox_input")
check_input.click()
is_checked = check_input.is_selected()
assert is_checked == False
# Handle the email input field
email_input = driver.find_element(By.NAME, "email_input")
email_input.clear() # Clear field
email = "admin@localhost.dev"
email_input.send_keys(email) # Enter text
# Verify input
data = email_input.get_attribute("value")
assert data == email
# Clear the email input field again
email_input.clear()
data = email_input.get_attribute("value")
assert data == ""
# Quit the driver
driver.quit()
// Navigate to Url
driver.Navigate().GoToUrl("https://www.selenium.dev/selenium/web/inputs.html");
// Click on the element
IWebElement checkInput = driver.FindElement(By.Name("checkbox_input"));
checkInput.Click();/examples/dotnet/SeleniumDocs/Elements/InteractionTest.cs
using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using OpenQA.Selenium;
using OpenQA.Selenium.Chrome;
namespace SeleniumDocs.Elements
{
[TestClass]
public class InteractionTest
{
[TestMethod]
public void TestInteractionCommands()
{
IWebDriver driver = new ChromeDriver();
driver.Manage().Timeouts().ImplicitWait = TimeSpan.FromMilliseconds(500);
// Navigate to Url
driver.Navigate().GoToUrl("https://www.selenium.dev/selenium/web/inputs.html");
// Click on the element
IWebElement checkInput = driver.FindElement(By.Name("checkbox_input"));
checkInput.Click();
//Verify
Boolean isChecked = checkInput.Selected;
Assert.AreEqual(isChecked, false);
//SendKeys
// Clear field to empty it from any previous data
IWebElement emailInput = driver.FindElement(By.Name("email_input"));
emailInput.Clear();
//Enter Text
String email = "admin@localhost.dev";
emailInput.SendKeys(email);
//Verify
String data = emailInput.GetAttribute("value");
Assert.AreEqual(data, email);
//Clear Element
// Clear field to empty it from any previous data
emailInput.Clear();
data = emailInput.GetAttribute("value");
//Verify
Assert.AreEqual(data, "");
//Quit the browser
driver.Quit();
}
}
} driver.find_element(name: 'color_input').click/examples/ruby/spec/elements/interaction_spec.rb
# frozen_string_literal: true
require 'spec_helper'
RSpec.describe 'Element Interaction' do
let(:driver) { start_session }
before { driver.get 'https://www.selenium.dev/selenium/web/inputs.html' }
it 'clicks an element' do
driver.find_element(name: 'color_input').click
end
it 'clears and send keys to an element' do
driver.find_element(name: 'email_input').clear
driver.find_element(name: 'email_input').send_keys 'admin@localhost.dev'
end
end
await submitButton.click();/examples/javascript/test/getting_started/firstScript.spec.js
const {By, Builder, Browser} = require('selenium-webdriver');
const assert = require("assert");
(async function firstTest() {
let driver;
try {
driver = await new Builder().forBrowser(Browser.CHROME).build();
await driver.get('https://www.selenium.dev/selenium/web/web-form.html');
let title = await driver.getTitle();
assert.equal("Web form", title);
await driver.manage().setTimeouts({implicit: 500});
let textBox = await driver.findElement(By.name('my-text'));
let submitButton = await driver.findElement(By.css('button'));
await textBox.sendKeys('Selenium');
await submitButton.click();
let message = await driver.findElement(By.id('message'));
let value = await message.getText();
assert.equal("Received!", value);
} catch (e) {
console.log(e)
} finally {
await driver.quit();
}
}())
// Navigate to Url
driver.get("https://www.selenium.dev/selenium/web/inputs.html")
// Click the element
driver.findElement(By.name("color_input")).click();
发送键位
元素发送键位命令
将录入提供的键位到 可编辑的 元素.
通常, 这意味着元素是具有 文本 类型的表单的输入元素或具有 内容可编辑 属性的元素.
如果不可编辑, 则返回
无效元素状态 错误.
以下 是WebDriver支持的按键列表.
// Clear field to empty it from any previous data
WebElement emailInput = driver.findElement(By.name("email_input"));
emailInput.clear();
// Enter Text
String email = "admin@localhost.dev";
emailInput.sendKeys(email);/examples/java/src/test/java/dev/selenium/elements/InteractionTest.java
package dev.selenium.elements;
import org.junit.jupiter.api.Test;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import java.time.Duration;
import static org.junit.jupiter.api.Assertions.assertEquals;
public class InteractionTest {
@Test
public void interactWithElements() {
WebDriver driver = new ChromeDriver();
driver.manage().timeouts().implicitlyWait(Duration.ofMillis(500));
// Navigate to Url
driver.get("https://www.selenium.dev/selenium/web/inputs.html");
// Click on the element
WebElement checkInput = driver.findElement(By.name("checkbox_input"));
checkInput.click();
Boolean isChecked = checkInput.isSelected();
assertEquals(isChecked, false);
// SendKeys
// Clear field to empty it from any previous data
WebElement emailInput = driver.findElement(By.name("email_input"));
emailInput.clear();
// Enter Text
String email = "admin@localhost.dev";
emailInput.sendKeys(email);
// Verify
String data = emailInput.getAttribute("value");
assertEquals(data, email);
// Clear Element
// Clear field to empty it from any previous data
emailInput.clear();
data = emailInput.getAttribute("value");
assertEquals(data, "");
driver.quit();
}
} # Handle the email input field
email_input = driver.find_element(By.NAME, "email_input")
email_input.clear() # Clear field
email = "admin@localhost.dev"
email_input.send_keys(email) # Enter text/examples/python/tests/elements/test_interaction.py
from selenium import webdriver
from selenium.webdriver.common.by import By
import pytest
def test_interactions():
# Initialize WebDriver
driver = webdriver.Chrome()
driver.implicitly_wait(0.5)
# Navigate to URL
driver.get("https://www.selenium.dev/selenium/web/inputs.html")
# Click on the checkbox
check_input = driver.find_element(By.NAME, "checkbox_input")
check_input.click()
is_checked = check_input.is_selected()
assert is_checked == False
# Handle the email input field
email_input = driver.find_element(By.NAME, "email_input")
email_input.clear() # Clear field
email = "admin@localhost.dev"
email_input.send_keys(email) # Enter text
# Verify input
data = email_input.get_attribute("value")
assert data == email
# Clear the email input field again
email_input.clear()
data = email_input.get_attribute("value")
assert data == ""
# Quit the driver
driver.quit()
//SendKeys
// Clear field to empty it from any previous data
IWebElement emailInput = driver.FindElement(By.Name("email_input"));
emailInput.Clear();
//Enter Text
String email = "admin@localhost.dev";
emailInput.SendKeys(email);/examples/dotnet/SeleniumDocs/Elements/InteractionTest.cs
using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using OpenQA.Selenium;
using OpenQA.Selenium.Chrome;
namespace SeleniumDocs.Elements
{
[TestClass]
public class InteractionTest
{
[TestMethod]
public void TestInteractionCommands()
{
IWebDriver driver = new ChromeDriver();
driver.Manage().Timeouts().ImplicitWait = TimeSpan.FromMilliseconds(500);
// Navigate to Url
driver.Navigate().GoToUrl("https://www.selenium.dev/selenium/web/inputs.html");
// Click on the element
IWebElement checkInput = driver.FindElement(By.Name("checkbox_input"));
checkInput.Click();
//Verify
Boolean isChecked = checkInput.Selected;
Assert.AreEqual(isChecked, false);
//SendKeys
// Clear field to empty it from any previous data
IWebElement emailInput = driver.FindElement(By.Name("email_input"));
emailInput.Clear();
//Enter Text
String email = "admin@localhost.dev";
emailInput.SendKeys(email);
//Verify
String data = emailInput.GetAttribute("value");
Assert.AreEqual(data, email);
//Clear Element
// Clear field to empty it from any previous data
emailInput.Clear();
data = emailInput.GetAttribute("value");
//Verify
Assert.AreEqual(data, "");
//Quit the browser
driver.Quit();
}
}
} driver.find_element(name: 'email_input').send_keys 'admin@localhost.dev'/examples/ruby/spec/elements/interaction_spec.rb
# frozen_string_literal: true
require 'spec_helper'
RSpec.describe 'Element Interaction' do
let(:driver) { start_session }
before { driver.get 'https://www.selenium.dev/selenium/web/inputs.html' }
it 'clicks an element' do
driver.find_element(name: 'color_input').click
end
it 'clears and send keys to an element' do
driver.find_element(name: 'email_input').clear
driver.find_element(name: 'email_input').send_keys 'admin@localhost.dev'
end
end
let inputField = await driver.findElement(By.name('no_type'));/examples/javascript/test/elements/interactions.spec.js
const {By, Browser, Builder} = require('selenium-webdriver');
const assert = require("node:assert");
describe('Element Interactions', function () {
let driver;
before(async function () {
driver = new Builder()
.forBrowser(Browser.CHROME)
.build();
});
after(async () => await driver.quit());
it('should Clear input and send keys into input field', async function () {
try {
await driver.get('https://www.selenium.dev/selenium/web/inputs.html');
let inputField = await driver.findElement(By.name('no_type'));
await inputField.clear();
await inputField.sendKeys('Selenium');
const text = await inputField.getAttribute('value');
assert.strictEqual(text, "Selenium");
} catch (e) {
console.log(e)
}
});
});
// Navigate to Url
driver.get("https://www.selenium.dev/selenium/web/inputs.html")
//Clear field to empty it from any previous data
driver.findElement(By.name("email_input")).clear()
// Enter text
driver.findElement(By.name("email_input")).sendKeys("admin@localhost.dev")
清除
元素清除命令
重置元素的内容.
这要求元素 可编辑,
且 可重置.
通常, 这意味着元素是具有 文本 类型的表单的输入元素或具有 内容可编辑 属性的元素.
如果不满足这些条件, 将返回
无效元素状态 错误.
// Clear field to empty it from any previous data
emailInput.clear();
data = emailInput.getAttribute("value");/examples/java/src/test/java/dev/selenium/elements/InteractionTest.java
package dev.selenium.elements;
import org.junit.jupiter.api.Test;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import java.time.Duration;
import static org.junit.jupiter.api.Assertions.assertEquals;
public class InteractionTest {
@Test
public void interactWithElements() {
WebDriver driver = new ChromeDriver();
driver.manage().timeouts().implicitlyWait(Duration.ofMillis(500));
// Navigate to Url
driver.get("https://www.selenium.dev/selenium/web/inputs.html");
// Click on the element
WebElement checkInput = driver.findElement(By.name("checkbox_input"));
checkInput.click();
Boolean isChecked = checkInput.isSelected();
assertEquals(isChecked, false);
// SendKeys
// Clear field to empty it from any previous data
WebElement emailInput = driver.findElement(By.name("email_input"));
emailInput.clear();
// Enter Text
String email = "admin@localhost.dev";
emailInput.sendKeys(email);
// Verify
String data = emailInput.getAttribute("value");
assertEquals(data, email);
// Clear Element
// Clear field to empty it from any previous data
emailInput.clear();
data = emailInput.getAttribute("value");
assertEquals(data, "");
driver.quit();
}
} email_input.clear()/examples/python/tests/elements/test_interaction.py
from selenium import webdriver
from selenium.webdriver.common.by import By
import pytest
def test_interactions():
# Initialize WebDriver
driver = webdriver.Chrome()
driver.implicitly_wait(0.5)
# Navigate to URL
driver.get("https://www.selenium.dev/selenium/web/inputs.html")
# Click on the checkbox
check_input = driver.find_element(By.NAME, "checkbox_input")
check_input.click()
is_checked = check_input.is_selected()
assert is_checked == False
# Handle the email input field
email_input = driver.find_element(By.NAME, "email_input")
email_input.clear() # Clear field
email = "admin@localhost.dev"
email_input.send_keys(email) # Enter text
# Verify input
data = email_input.get_attribute("value")
assert data == email
# Clear the email input field again
email_input.clear()
data = email_input.get_attribute("value")
assert data == ""
# Quit the driver
driver.quit()
//Clear Element
// Clear field to empty it from any previous data
emailInput.Clear();
data = emailInput.GetAttribute("value");/examples/dotnet/SeleniumDocs/Elements/InteractionTest.cs
using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using OpenQA.Selenium;
using OpenQA.Selenium.Chrome;
namespace SeleniumDocs.Elements
{
[TestClass]
public class InteractionTest
{
[TestMethod]
public void TestInteractionCommands()
{
IWebDriver driver = new ChromeDriver();
driver.Manage().Timeouts().ImplicitWait = TimeSpan.FromMilliseconds(500);
// Navigate to Url
driver.Navigate().GoToUrl("https://www.selenium.dev/selenium/web/inputs.html");
// Click on the element
IWebElement checkInput = driver.FindElement(By.Name("checkbox_input"));
checkInput.Click();
//Verify
Boolean isChecked = checkInput.Selected;
Assert.AreEqual(isChecked, false);
//SendKeys
// Clear field to empty it from any previous data
IWebElement emailInput = driver.FindElement(By.Name("email_input"));
emailInput.Clear();
//Enter Text
String email = "admin@localhost.dev";
emailInput.SendKeys(email);
//Verify
String data = emailInput.GetAttribute("value");
Assert.AreEqual(data, email);
//Clear Element
// Clear field to empty it from any previous data
emailInput.Clear();
data = emailInput.GetAttribute("value");
//Verify
Assert.AreEqual(data, "");
//Quit the browser
driver.Quit();
}
}
} driver.find_element(name: 'email_input').clear/examples/ruby/spec/elements/interaction_spec.rb
# frozen_string_literal: true
require 'spec_helper'
RSpec.describe 'Element Interaction' do
let(:driver) { start_session }
before { driver.get 'https://www.selenium.dev/selenium/web/inputs.html' }
it 'clicks an element' do
driver.find_element(name: 'color_input').click
end
it 'clears and send keys to an element' do
driver.find_element(name: 'email_input').clear
driver.find_element(name: 'email_input').send_keys 'admin@localhost.dev'
end
end
await driver.get('https://www.selenium.dev/selenium/web/inputs.html');/examples/javascript/test/elements/interactions.spec.js
const {By, Browser, Builder} = require('selenium-webdriver');
const assert = require("node:assert");
describe('Element Interactions', function () {
let driver;
before(async function () {
driver = new Builder()
.forBrowser(Browser.CHROME)
.build();
});
after(async () => await driver.quit());
it('should Clear input and send keys into input field', async function () {
try {
await driver.get('https://www.selenium.dev/selenium/web/inputs.html');
let inputField = await driver.findElement(By.name('no_type'));
await inputField.clear();
await inputField.sendKeys('Selenium');
const text = await inputField.getAttribute('value');
assert.strictEqual(text, "Selenium");
} catch (e) {
console.log(e)
}
});
});
// Navigate to Url
driver.get("https://www.selenium.dev/selenium/web/inputs.html")
//Clear field to empty it from any previous data
driver.findElement(By.name("email_input")).clear()
提交
在Selenium 4中, 不再通过单独的端点以及脚本执行的方法来实现. 因此, 建议不要使用此方法, 而是单击相应的表单提交按钮.
3 - 定位策略
定位器是在页面上标识元素的一种方法。它是传送给 查找元素 方法的参数。
查看 鼓励测试练习 寻找 定位器的小技巧, 包含在查找方法中,不同时间,不同原因下,单独声明的定位器的使用方法。
元素选择策略
在 WebDriver 中有 8 种不同的内置元素定位策略:
| 定位器 Locator | 描述 |
|---|---|
| class name | 定位class属性与搜索值匹配的元素(不允许使用复合类名) |
| css selector | 定位 CSS 选择器匹配的元素 |
| id | 定位 id 属性与搜索值匹配的元素 |
| name | 定位 name 属性与搜索值匹配的元素 |
| link text | 定位link text可视文本与搜索值完全匹配的锚元素 |
| partial link text | 定位link text可视文本部分与搜索值部分匹配的锚点元素。如果匹配多个元素,则只选择第一个元素。 |
| tag name | 定位标签名称与搜索值匹配的元素 |
| xpath | 定位与 XPath 表达式匹配的元素 |
Creating Locators
To work on a web element using Selenium, we need to first locate it on the web page. Selenium provides us above mentioned ways, using which we can locate element on the page. To understand and create locator we will use the following HTML snippet.
<html>
<body>
<style>
.information {
background-color: white;
color: black;
padding: 10px;
}
</style>
<h2>Contact Selenium</h2>
<form>
<input type="radio" name="gender" value="m" />Male
<input type="radio" name="gender" value="f" />Female <br>
<br>
<label for="fname">First name:</label><br>
<input class="information" type="text" id="fname" name="fname" value="Jane"><br><br>
<label for="lname">Last name:</label><br>
<input class="information" type="text" id="lname" name="lname" value="Doe"><br><br>
<label for="newsletter">Newsletter:</label>
<input type="checkbox" name="newsletter" value="1" /><br><br>
<input type="submit" value="Submit">
</form>
<p>To know more about Selenium, visit the official page
<a href ="www.selenium.dev">Selenium Official Page</a>
</p>
</body>
</html>
class name
The HTML page web element can have attribute class. We can see an example in the above shown HTML snippet. We can identify these elements using the class name locator available in Selenium.
WebElement element = driver.findElement(By.className("information"));/examples/java/src/test/java/dev/selenium/elements/LocatorTest.java
import java.util.List;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.support.pagefactory.ByAll;
import org.openqa.selenium.support.pagefactory.ByChained;
public class LocatorTest {
private WebDriver driver;
@BeforeEach
public void setUp() {
// Initialize the driver before each test
driver = new ChromeDriver();
driver.get("https://www.selenium.dev/selenium/web/locators_tests/locators.html");
}
@AfterEach
public void tearDown() {
// Close the browser after each test
if (driver != null) {
driver.quit();
}
}
@Test
public void testClassName() {
WebElement element = driver.findElement(By.className("information"));
Assertions.assertNotNull(element);
Assertions.assertEquals("input", element.getTagName());
}
@Test
public void testCssSelector() {
WebElement element = driver.findElement(By.cssSelector("#fname"));
Assertions.assertNotNull(element);
Assertions.assertEquals("Jane", element.getAttribute("value"));
}
@Test
public void testId() {
WebElement element = driver.findElement(By.id("lname"));
Assertions.assertNotNull(element);
Assertions.assertEquals("Doe", element.getAttribute("value"));
}
@Test
public void testName() {
WebElement element = driver.findElement(By.name("newsletter"));
Assertions.assertNotNull(element);
Assertions.assertEquals("input", element.getTagName());
}
@Test
public void testLinkText() {
WebElement element = driver.findElement(By.linkText("Selenium Official Page"));
Assertions.assertNotNull(element);
Assertions.assertEquals("https://www.selenium.dev/", element.getAttribute("href"));
}
@Test
public void testPartialLinkText() {
WebElement element = driver.findElement(By.partialLinkText("Official Page"));
Assertions.assertNotNull(element);
Assertions.assertEquals("https://www.selenium.dev/", element.getAttribute("href"));
}
@Test
public void testTagName() {
WebElement element = driver.findElement(By.tagName("a"));
Assertions.assertNotNull(element);
Assertions.assertEquals("https://www.selenium.dev/", element.getAttribute("href"));
}
@Test
public void testXpath() {
WebElement element = driver.findElement(By.xpath("//input[@value='f']"));
Assertions.assertNotNull(element);
Assertions.assertEquals("radio", element.getAttribute("type"));
}
@Test
public void testByAll() {
driver.get("https://www.selenium.dev/selenium/web/login.html");
By locator = new ByAll(By.id("password-field"), By.id("username-field"));
List<WebElement> loginInputs = driver.findElements(locator);
Assertions.assertEquals(2, loginInputs.size());
}
@Test
public void testByChained() {
driver.get("https://www.selenium.dev/selenium/web/login.html");
By locator = new ByChained(By.id("login-form"), By.tagName("input"));
WebElement usernameInput = driver.findElement(locator);
Assertions.assertEquals("Username", usernameInput.getAttribute("placeholder"));
}
}
driver = webdriver.Chrome()
driver.get("https://www.selenium.dev/selenium/web/locators_tests/locators.html")
element = driver.find_element(By.CLASS_NAME, "information")/examples/python/tests/elements/test_locators.py
import pytest
from selenium import webdriver
from selenium.webdriver.common.by import By
def test_class_name():
driver = webdriver.Chrome()
driver.get("https://www.selenium.dev/selenium/web/locators_tests/locators.html")
element = driver.find_element(By.CLASS_NAME, "information")
assert element is not None
assert element.tag_name == "input"
driver.quit()
def test_css_selector(driver):
driver = webdriver.Chrome()
driver.get("https://www.selenium.dev/selenium/web/locators_tests/locators.html")
element = driver.find_element(By.CSS_SELECTOR, "#fname")
assert element is not None
assert element.get_attribute("value") == "Jane"
driver.quit()
def test_id(driver):
driver = webdriver.Chrome()
driver.get("https://www.selenium.dev/selenium/web/locators_tests/locators.html")
element = driver.find_element(By.ID, "lname")
assert element is not None
assert element.get_attribute("value") == "Doe"
driver.quit()
def test_name(driver):
driver = webdriver.Chrome()
driver.get("https://www.selenium.dev/selenium/web/locators_tests/locators.html")
element = driver.find_element(By.NAME, "newsletter")
assert element is not None
assert element.tag_name == "input"
driver.quit()
def test_link_text(driver):
driver = webdriver.Chrome()
driver.get("https://www.selenium.dev/selenium/web/locators_tests/locators.html")
element = driver.find_element(By.LINK_TEXT, "Selenium Official Page")
assert element is not None
assert element.get_attribute("href") == "https://www.selenium.dev/"
driver.quit()
def test_partial_link_text(driver):
driver = webdriver.Chrome()
driver.get("https://www.selenium.dev/selenium/web/locators_tests/locators.html")
element = driver.find_element(By.PARTIAL_LINK_TEXT, "Official Page")
assert element is not None
assert element.get_attribute("href") == "https://www.selenium.dev/"
driver.quit()
def test_tag_name(driver):
driver = webdriver.Chrome()
driver.get("https://www.selenium.dev/selenium/web/locators_tests/locators.html")
element = driver.find_element(By.TAG_NAME, "a")
assert element is not None
assert element.get_attribute("href") == "https://www.selenium.dev/"
driver.quit()
def test_xpath(driver):
driver = webdriver.Chrome()
driver.get("https://www.selenium.dev/selenium/web/locators_tests/locators.html")
element = driver.find_element(By.XPATH, "//input[@value='f']")
assert element is not None
assert element.get_attribute("type") == "radio"
driver.quit()
var driver = new ChromeDriver();
driver.FindElement(By.ClassName("information"));
driver.find_element(class: 'information')/examples/ruby/spec/elements/locators_spec.rb
# frozen_string_literal: true
require 'spec_helper'
RSpec.describe 'Element Locators', skip: 'These are reference following the documentation example' do
it 'finds element by class name' do
driver.find_element(class: 'information')
end
it 'finds element by css selector' do
driver.find_element(css: '#fname')
end
it 'finds element by id' do
driver.find_element(id: 'lname')
end
it 'find element by name' do
driver.find_element(name: 'newsletter')
end
it 'finds element by link text' do
driver.find_element(link_text: 'Selenium Official Page')
end
it 'finds element by partial link text' do
driver.find_element(partial_link_text: 'Official Page')
end
it 'finds element by tag name' do
driver.find_element(tag_name: 'a')
end
it 'finds element by xpath' do
driver.find_element(xpath: "//input[@value='f']")
end
context 'with relative locators' do
it 'finds element above' do
driver.find_element({relative: {tag_name: 'input', above: {id: 'password'}}})
end
it 'finds element below' do
driver.find_element({relative: {tag_name: 'input', below: {id: 'email'}}})
end
it 'finds element to the left' do
driver.find_element({relative: {tag_name: 'button', left: {id: 'submit'}}})
end
it 'finds element to the right' do
driver.find_element({relative: {tag_name: 'button', right: {id: 'cancel'}}})
end
it 'finds near element' do
driver.find_element({relative: {tag_name: 'input', near: {id: 'lbl-email'}}})
end
it 'chains relative locators' do
driver.find_element({relative: {tag_name: 'button', below: {id: 'email'}, right: {id: 'cancel'}}})
end
end
end
let driver = await new Builder().forBrowser('chrome').build();
const loc = await driver.findElement(By.className('information'));
val driver = ChromeDriver()
val loc: WebElement = driver.findElement(By.className("information"))
css selector
CSS is the language used to style HTML pages. We can use css selector locator strategy to identify the element on the page. If the element has an id, we create the locator as css = #id. Otherwise the format we follow is css =[attribute=value] . Let us see an example from above HTML snippet. We will create locator for First Name textbox, using css.
WebElement element = driver.findElement(By.cssSelector("#fname"));/examples/java/src/test/java/dev/selenium/elements/LocatorTest.java
import java.util.List;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.support.pagefactory.ByAll;
import org.openqa.selenium.support.pagefactory.ByChained;
public class LocatorTest {
private WebDriver driver;
@BeforeEach
public void setUp() {
// Initialize the driver before each test
driver = new ChromeDriver();
driver.get("https://www.selenium.dev/selenium/web/locators_tests/locators.html");
}
@AfterEach
public void tearDown() {
// Close the browser after each test
if (driver != null) {
driver.quit();
}
}
@Test
public void testClassName() {
WebElement element = driver.findElement(By.className("information"));
Assertions.assertNotNull(element);
Assertions.assertEquals("input", element.getTagName());
}
@Test
public void testCssSelector() {
WebElement element = driver.findElement(By.cssSelector("#fname"));
Assertions.assertNotNull(element);
Assertions.assertEquals("Jane", element.getAttribute("value"));
}
@Test
public void testId() {
WebElement element = driver.findElement(By.id("lname"));
Assertions.assertNotNull(element);
Assertions.assertEquals("Doe", element.getAttribute("value"));
}
@Test
public void testName() {
WebElement element = driver.findElement(By.name("newsletter"));
Assertions.assertNotNull(element);
Assertions.assertEquals("input", element.getTagName());
}
@Test
public void testLinkText() {
WebElement element = driver.findElement(By.linkText("Selenium Official Page"));
Assertions.assertNotNull(element);
Assertions.assertEquals("https://www.selenium.dev/", element.getAttribute("href"));
}
@Test
public void testPartialLinkText() {
WebElement element = driver.findElement(By.partialLinkText("Official Page"));
Assertions.assertNotNull(element);
Assertions.assertEquals("https://www.selenium.dev/", element.getAttribute("href"));
}
@Test
public void testTagName() {
WebElement element = driver.findElement(By.tagName("a"));
Assertions.assertNotNull(element);
Assertions.assertEquals("https://www.selenium.dev/", element.getAttribute("href"));
}
@Test
public void testXpath() {
WebElement element = driver.findElement(By.xpath("//input[@value='f']"));
Assertions.assertNotNull(element);
Assertions.assertEquals("radio", element.getAttribute("type"));
}
@Test
public void testByAll() {
driver.get("https://www.selenium.dev/selenium/web/login.html");
By locator = new ByAll(By.id("password-field"), By.id("username-field"));
List<WebElement> loginInputs = driver.findElements(locator);
Assertions.assertEquals(2, loginInputs.size());
}
@Test
public void testByChained() {
driver.get("https://www.selenium.dev/selenium/web/login.html");
By locator = new ByChained(By.id("login-form"), By.tagName("input"));
WebElement usernameInput = driver.findElement(locator);
Assertions.assertEquals("Username", usernameInput.getAttribute("placeholder"));
}
}
driver = webdriver.Chrome()
driver.get("https://www.selenium.dev/selenium/web/locators_tests/locators.html")
element = driver.find_element(By.CSS_SELECTOR, "#fname")/examples/python/tests/elements/test_locators.py
import pytest
from selenium import webdriver
from selenium.webdriver.common.by import By
def test_class_name():
driver = webdriver.Chrome()
driver.get("https://www.selenium.dev/selenium/web/locators_tests/locators.html")
element = driver.find_element(By.CLASS_NAME, "information")
assert element is not None
assert element.tag_name == "input"
driver.quit()
def test_css_selector(driver):
driver = webdriver.Chrome()
driver.get("https://www.selenium.dev/selenium/web/locators_tests/locators.html")
element = driver.find_element(By.CSS_SELECTOR, "#fname")
assert element is not None
assert element.get_attribute("value") == "Jane"
driver.quit()
def test_id(driver):
driver = webdriver.Chrome()
driver.get("https://www.selenium.dev/selenium/web/locators_tests/locators.html")
element = driver.find_element(By.ID, "lname")
assert element is not None
assert element.get_attribute("value") == "Doe"
driver.quit()
def test_name(driver):
driver = webdriver.Chrome()
driver.get("https://www.selenium.dev/selenium/web/locators_tests/locators.html")
element = driver.find_element(By.NAME, "newsletter")
assert element is not None
assert element.tag_name == "input"
driver.quit()
def test_link_text(driver):
driver = webdriver.Chrome()
driver.get("https://www.selenium.dev/selenium/web/locators_tests/locators.html")
element = driver.find_element(By.LINK_TEXT, "Selenium Official Page")
assert element is not None
assert element.get_attribute("href") == "https://www.selenium.dev/"
driver.quit()
def test_partial_link_text(driver):
driver = webdriver.Chrome()
driver.get("https://www.selenium.dev/selenium/web/locators_tests/locators.html")
element = driver.find_element(By.PARTIAL_LINK_TEXT, "Official Page")
assert element is not None
assert element.get_attribute("href") == "https://www.selenium.dev/"
driver.quit()
def test_tag_name(driver):
driver = webdriver.Chrome()
driver.get("https://www.selenium.dev/selenium/web/locators_tests/locators.html")
element = driver.find_element(By.TAG_NAME, "a")
assert element is not None
assert element.get_attribute("href") == "https://www.selenium.dev/"
driver.quit()
def test_xpath(driver):
driver = webdriver.Chrome()
driver.get("https://www.selenium.dev/selenium/web/locators_tests/locators.html")
element = driver.find_element(By.XPATH, "//input[@value='f']")
assert element is not None
assert element.get_attribute("type") == "radio"
driver.quit()
var driver = new ChromeDriver();
driver.FindElement(By.CssSelector("#fname"));
driver.find_element(css: '#fname')/examples/ruby/spec/elements/locators_spec.rb
# frozen_string_literal: true
require 'spec_helper'
RSpec.describe 'Element Locators', skip: 'These are reference following the documentation example' do
it 'finds element by class name' do
driver.find_element(class: 'information')
end
it 'finds element by css selector' do
driver.find_element(css: '#fname')
end
it 'finds element by id' do
driver.find_element(id: 'lname')
end
it 'find element by name' do
driver.find_element(name: 'newsletter')
end
it 'finds element by link text' do
driver.find_element(link_text: 'Selenium Official Page')
end
it 'finds element by partial link text' do
driver.find_element(partial_link_text: 'Official Page')
end
it 'finds element by tag name' do
driver.find_element(tag_name: 'a')
end
it 'finds element by xpath' do
driver.find_element(xpath: "//input[@value='f']")
end
context 'with relative locators' do
it 'finds element above' do
driver.find_element({relative: {tag_name: 'input', above: {id: 'password'}}})
end
it 'finds element below' do
driver.find_element({relative: {tag_name: 'input', below: {id: 'email'}}})
end
it 'finds element to the left' do
driver.find_element({relative: {tag_name: 'button', left: {id: 'submit'}}})
end
it 'finds element to the right' do
driver.find_element({relative: {tag_name: 'button', right: {id: 'cancel'}}})
end
it 'finds near element' do
driver.find_element({relative: {tag_name: 'input', near: {id: 'lbl-email'}}})
end
it 'chains relative locators' do
driver.find_element({relative: {tag_name: 'button', below: {id: 'email'}, right: {id: 'cancel'}}})
end
end
end
let driver = await new Builder().forBrowser('chrome').build();
const loc = await driver.findElement(By.css('#fname'));
val driver = ChromeDriver()
val loc: WebElement = driver.findElement(By.css("#fname"))
id
We can use the ID attribute available with element in a web page to locate it. Generally the ID property should be unique for a element on the web page. We will identify the Last Name field using it.
WebElement element = driver.findElement(By.id("lname"));/examples/java/src/test/java/dev/selenium/elements/LocatorTest.java
import java.util.List;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.support.pagefactory.ByAll;
import org.openqa.selenium.support.pagefactory.ByChained;
public class LocatorTest {
private WebDriver driver;
@BeforeEach
public void setUp() {
// Initialize the driver before each test
driver = new ChromeDriver();
driver.get("https://www.selenium.dev/selenium/web/locators_tests/locators.html");
}
@AfterEach
public void tearDown() {
// Close the browser after each test
if (driver != null) {
driver.quit();
}
}
@Test
public void testClassName() {
WebElement element = driver.findElement(By.className("information"));
Assertions.assertNotNull(element);
Assertions.assertEquals("input", element.getTagName());
}
@Test
public void testCssSelector() {
WebElement element = driver.findElement(By.cssSelector("#fname"));
Assertions.assertNotNull(element);
Assertions.assertEquals("Jane", element.getAttribute("value"));
}
@Test
public void testId() {
WebElement element = driver.findElement(By.id("lname"));
Assertions.assertNotNull(element);
Assertions.assertEquals("Doe", element.getAttribute("value"));
}
@Test
public void testName() {
WebElement element = driver.findElement(By.name("newsletter"));
Assertions.assertNotNull(element);
Assertions.assertEquals("input", element.getTagName());
}
@Test
public void testLinkText() {
WebElement element = driver.findElement(By.linkText("Selenium Official Page"));
Assertions.assertNotNull(element);
Assertions.assertEquals("https://www.selenium.dev/", element.getAttribute("href"));
}
@Test
public void testPartialLinkText() {
WebElement element = driver.findElement(By.partialLinkText("Official Page"));
Assertions.assertNotNull(element);
Assertions.assertEquals("https://www.selenium.dev/", element.getAttribute("href"));
}
@Test
public void testTagName() {
WebElement element = driver.findElement(By.tagName("a"));
Assertions.assertNotNull(element);
Assertions.assertEquals("https://www.selenium.dev/", element.getAttribute("href"));
}
@Test
public void testXpath() {
WebElement element = driver.findElement(By.xpath("//input[@value='f']"));
Assertions.assertNotNull(element);
Assertions.assertEquals("radio", element.getAttribute("type"));
}
@Test
public void testByAll() {
driver.get("https://www.selenium.dev/selenium/web/login.html");
By locator = new ByAll(By.id("password-field"), By.id("username-field"));
List<WebElement> loginInputs = driver.findElements(locator);
Assertions.assertEquals(2, loginInputs.size());
}
@Test
public void testByChained() {
driver.get("https://www.selenium.dev/selenium/web/login.html");
By locator = new ByChained(By.id("login-form"), By.tagName("input"));
WebElement usernameInput = driver.findElement(locator);
Assertions.assertEquals("Username", usernameInput.getAttribute("placeholder"));
}
}
driver = webdriver.Chrome()
driver.get("https://www.selenium.dev/selenium/web/locators_tests/locators.html")
element = driver.find_element(By.ID, "lname")/examples/python/tests/elements/test_locators.py
import pytest
from selenium import webdriver
from selenium.webdriver.common.by import By
def test_class_name():
driver = webdriver.Chrome()
driver.get("https://www.selenium.dev/selenium/web/locators_tests/locators.html")
element = driver.find_element(By.CLASS_NAME, "information")
assert element is not None
assert element.tag_name == "input"
driver.quit()
def test_css_selector(driver):
driver = webdriver.Chrome()
driver.get("https://www.selenium.dev/selenium/web/locators_tests/locators.html")
element = driver.find_element(By.CSS_SELECTOR, "#fname")
assert element is not None
assert element.get_attribute("value") == "Jane"
driver.quit()
def test_id(driver):
driver = webdriver.Chrome()
driver.get("https://www.selenium.dev/selenium/web/locators_tests/locators.html")
element = driver.find_element(By.ID, "lname")
assert element is not None
assert element.get_attribute("value") == "Doe"
driver.quit()
def test_name(driver):
driver = webdriver.Chrome()
driver.get("https://www.selenium.dev/selenium/web/locators_tests/locators.html")
element = driver.find_element(By.NAME, "newsletter")
assert element is not None
assert element.tag_name == "input"
driver.quit()
def test_link_text(driver):
driver = webdriver.Chrome()
driver.get("https://www.selenium.dev/selenium/web/locators_tests/locators.html")
element = driver.find_element(By.LINK_TEXT, "Selenium Official Page")
assert element is not None
assert element.get_attribute("href") == "https://www.selenium.dev/"
driver.quit()
def test_partial_link_text(driver):
driver = webdriver.Chrome()
driver.get("https://www.selenium.dev/selenium/web/locators_tests/locators.html")
element = driver.find_element(By.PARTIAL_LINK_TEXT, "Official Page")
assert element is not None
assert element.get_attribute("href") == "https://www.selenium.dev/"
driver.quit()
def test_tag_name(driver):
driver = webdriver.Chrome()
driver.get("https://www.selenium.dev/selenium/web/locators_tests/locators.html")
element = driver.find_element(By.TAG_NAME, "a")
assert element is not None
assert element.get_attribute("href") == "https://www.selenium.dev/"
driver.quit()
def test_xpath(driver):
driver = webdriver.Chrome()
driver.get("https://www.selenium.dev/selenium/web/locators_tests/locators.html")
element = driver.find_element(By.XPATH, "//input[@value='f']")
assert element is not None
assert element.get_attribute("type") == "radio"
driver.quit()
var driver = new ChromeDriver();
driver.FindElement(By.Id("lname"));
driver.find_element(id: 'lname')/examples/ruby/spec/elements/locators_spec.rb
# frozen_string_literal: true
require 'spec_helper'
RSpec.describe 'Element Locators', skip: 'These are reference following the documentation example' do
it 'finds element by class name' do
driver.find_element(class: 'information')
end
it 'finds element by css selector' do
driver.find_element(css: '#fname')
end
it 'finds element by id' do
driver.find_element(id: 'lname')
end
it 'find element by name' do
driver.find_element(name: 'newsletter')
end
it 'finds element by link text' do
driver.find_element(link_text: 'Selenium Official Page')
end
it 'finds element by partial link text' do
driver.find_element(partial_link_text: 'Official Page')
end
it 'finds element by tag name' do
driver.find_element(tag_name: 'a')
end
it 'finds element by xpath' do
driver.find_element(xpath: "//input[@value='f']")
end
context 'with relative locators' do
it 'finds element above' do
driver.find_element({relative: {tag_name: 'input', above: {id: 'password'}}})
end
it 'finds element below' do
driver.find_element({relative: {tag_name: 'input', below: {id: 'email'}}})
end
it 'finds element to the left' do
driver.find_element({relative: {tag_name: 'button', left: {id: 'submit'}}})
end
it 'finds element to the right' do
driver.find_element({relative: {tag_name: 'button', right: {id: 'cancel'}}})
end
it 'finds near element' do
driver.find_element({relative: {tag_name: 'input', near: {id: 'lbl-email'}}})
end
it 'chains relative locators' do
driver.find_element({relative: {tag_name: 'button', below: {id: 'email'}, right: {id: 'cancel'}}})
end
end
end
let driver = await new Builder().forBrowser('chrome').build();
const loc = await driver.findElement(By.id('lname'));
val driver = ChromeDriver()
val loc: WebElement = driver.findElement(By.id("lname"))
name
We can use the NAME attribute available with element in a web page to locate it. Generally the NAME property should be unique for a element on the web page. We will identify the Newsletter checkbox using it.
WebElement element = driver.findElement(By.name("newsletter"));/examples/java/src/test/java/dev/selenium/elements/LocatorTest.java
import java.util.List;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.support.pagefactory.ByAll;
import org.openqa.selenium.support.pagefactory.ByChained;
public class LocatorTest {
private WebDriver driver;
@BeforeEach
public void setUp() {
// Initialize the driver before each test
driver = new ChromeDriver();
driver.get("https://www.selenium.dev/selenium/web/locators_tests/locators.html");
}
@AfterEach
public void tearDown() {
// Close the browser after each test
if (driver != null) {
driver.quit();
}
}
@Test
public void testClassName() {
WebElement element = driver.findElement(By.className("information"));
Assertions.assertNotNull(element);
Assertions.assertEquals("input", element.getTagName());
}
@Test
public void testCssSelector() {
WebElement element = driver.findElement(By.cssSelector("#fname"));
Assertions.assertNotNull(element);
Assertions.assertEquals("Jane", element.getAttribute("value"));
}
@Test
public void testId() {
WebElement element = driver.findElement(By.id("lname"));
Assertions.assertNotNull(element);
Assertions.assertEquals("Doe", element.getAttribute("value"));
}
@Test
public void testName() {
WebElement element = driver.findElement(By.name("newsletter"));
Assertions.assertNotNull(element);
Assertions.assertEquals("input", element.getTagName());
}
@Test
public void testLinkText() {
WebElement element = driver.findElement(By.linkText("Selenium Official Page"));
Assertions.assertNotNull(element);
Assertions.assertEquals("https://www.selenium.dev/", element.getAttribute("href"));
}
@Test
public void testPartialLinkText() {
WebElement element = driver.findElement(By.partialLinkText("Official Page"));
Assertions.assertNotNull(element);
Assertions.assertEquals("https://www.selenium.dev/", element.getAttribute("href"));
}
@Test
public void testTagName() {
WebElement element = driver.findElement(By.tagName("a"));
Assertions.assertNotNull(element);
Assertions.assertEquals("https://www.selenium.dev/", element.getAttribute("href"));
}
@Test
public void testXpath() {
WebElement element = driver.findElement(By.xpath("//input[@value='f']"));
Assertions.assertNotNull(element);
Assertions.assertEquals("radio", element.getAttribute("type"));
}
@Test
public void testByAll() {
driver.get("https://www.selenium.dev/selenium/web/login.html");
By locator = new ByAll(By.id("password-field"), By.id("username-field"));
List<WebElement> loginInputs = driver.findElements(locator);
Assertions.assertEquals(2, loginInputs.size());
}
@Test
public void testByChained() {
driver.get("https://www.selenium.dev/selenium/web/login.html");
By locator = new ByChained(By.id("login-form"), By.tagName("input"));
WebElement usernameInput = driver.findElement(locator);
Assertions.assertEquals("Username", usernameInput.getAttribute("placeholder"));
}
}
driver = webdriver.Chrome()
driver.get("https://www.selenium.dev/selenium/web/locators_tests/locators.html")
element = driver.find_element(By.NAME, "newsletter")/examples/python/tests/elements/test_locators.py
import pytest
from selenium import webdriver
from selenium.webdriver.common.by import By
def test_class_name():
driver = webdriver.Chrome()
driver.get("https://www.selenium.dev/selenium/web/locators_tests/locators.html")
element = driver.find_element(By.CLASS_NAME, "information")
assert element is not None
assert element.tag_name == "input"
driver.quit()
def test_css_selector(driver):
driver = webdriver.Chrome()
driver.get("https://www.selenium.dev/selenium/web/locators_tests/locators.html")
element = driver.find_element(By.CSS_SELECTOR, "#fname")
assert element is not None
assert element.get_attribute("value") == "Jane"
driver.quit()
def test_id(driver):
driver = webdriver.Chrome()
driver.get("https://www.selenium.dev/selenium/web/locators_tests/locators.html")
element = driver.find_element(By.ID, "lname")
assert element is not None
assert element.get_attribute("value") == "Doe"
driver.quit()
def test_name(driver):
driver = webdriver.Chrome()
driver.get("https://www.selenium.dev/selenium/web/locators_tests/locators.html")
element = driver.find_element(By.NAME, "newsletter")
assert element is not None
assert element.tag_name == "input"
driver.quit()
def test_link_text(driver):
driver = webdriver.Chrome()
driver.get("https://www.selenium.dev/selenium/web/locators_tests/locators.html")
element = driver.find_element(By.LINK_TEXT, "Selenium Official Page")
assert element is not None
assert element.get_attribute("href") == "https://www.selenium.dev/"
driver.quit()
def test_partial_link_text(driver):
driver = webdriver.Chrome()
driver.get("https://www.selenium.dev/selenium/web/locators_tests/locators.html")
element = driver.find_element(By.PARTIAL_LINK_TEXT, "Official Page")
assert element is not None
assert element.get_attribute("href") == "https://www.selenium.dev/"
driver.quit()
def test_tag_name(driver):
driver = webdriver.Chrome()
driver.get("https://www.selenium.dev/selenium/web/locators_tests/locators.html")
element = driver.find_element(By.TAG_NAME, "a")
assert element is not None
assert element.get_attribute("href") == "https://www.selenium.dev/"
driver.quit()
def test_xpath(driver):
driver = webdriver.Chrome()
driver.get("https://www.selenium.dev/selenium/web/locators_tests/locators.html")
element = driver.find_element(By.XPATH, "//input[@value='f']")
assert element is not None
assert element.get_attribute("type") == "radio"
driver.quit()
var driver = new ChromeDriver();
driver.FindElement(By.Name("newsletter"));
driver.find_element(name: 'newsletter')/examples/ruby/spec/elements/locators_spec.rb
# frozen_string_literal: true
require 'spec_helper'
RSpec.describe 'Element Locators', skip: 'These are reference following the documentation example' do
it 'finds element by class name' do
driver.find_element(class: 'information')
end
it 'finds element by css selector' do
driver.find_element(css: '#fname')
end
it 'finds element by id' do
driver.find_element(id: 'lname')
end
it 'find element by name' do
driver.find_element(name: 'newsletter')
end
it 'finds element by link text' do
driver.find_element(link_text: 'Selenium Official Page')
end
it 'finds element by partial link text' do
driver.find_element(partial_link_text: 'Official Page')
end
it 'finds element by tag name' do
driver.find_element(tag_name: 'a')
end
it 'finds element by xpath' do
driver.find_element(xpath: "//input[@value='f']")
end
context 'with relative locators' do
it 'finds element above' do
driver.find_element({relative: {tag_name: 'input', above: {id: 'password'}}})
end
it 'finds element below' do
driver.find_element({relative: {tag_name: 'input', below: {id: 'email'}}})
end
it 'finds element to the left' do
driver.find_element({relative: {tag_name: 'button', left: {id: 'submit'}}})
end
it 'finds element to the right' do
driver.find_element({relative: {tag_name: 'button', right: {id: 'cancel'}}})
end
it 'finds near element' do
driver.find_element({relative: {tag_name: 'input', near: {id: 'lbl-email'}}})
end
it 'chains relative locators' do
driver.find_element({relative: {tag_name: 'button', below: {id: 'email'}, right: {id: 'cancel'}}})
end
end
end
let driver = await new Builder().forBrowser('chrome').build();
const loc = await driver.findElement(By.name('newsletter'));
val driver = ChromeDriver()
val loc: WebElement = driver.findElement(By.name("newsletter"))
link text
If the element we want to locate is a link, we can use the link text locator to identify it on the web page. The link text is the text displayed of the link. In the HTML snippet shared, we have a link available, lets see how will we locate it.
WebElement element = driver.findElement(By.linkText("Selenium Official Page"));/examples/java/src/test/java/dev/selenium/elements/LocatorTest.java
import java.util.List;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.support.pagefactory.ByAll;
import org.openqa.selenium.support.pagefactory.ByChained;
public class LocatorTest {
private WebDriver driver;
@BeforeEach
public void setUp() {
// Initialize the driver before each test
driver = new ChromeDriver();
driver.get("https://www.selenium.dev/selenium/web/locators_tests/locators.html");
}
@AfterEach
public void tearDown() {
// Close the browser after each test
if (driver != null) {
driver.quit();
}
}
@Test
public void testClassName() {
WebElement element = driver.findElement(By.className("information"));
Assertions.assertNotNull(element);
Assertions.assertEquals("input", element.getTagName());
}
@Test
public void testCssSelector() {
WebElement element = driver.findElement(By.cssSelector("#fname"));
Assertions.assertNotNull(element);
Assertions.assertEquals("Jane", element.getAttribute("value"));
}
@Test
public void testId() {
WebElement element = driver.findElement(By.id("lname"));
Assertions.assertNotNull(element);
Assertions.assertEquals("Doe", element.getAttribute("value"));
}
@Test
public void testName() {
WebElement element = driver.findElement(By.name("newsletter"));
Assertions.assertNotNull(element);
Assertions.assertEquals("input", element.getTagName());
}
@Test
public void testLinkText() {
WebElement element = driver.findElement(By.linkText("Selenium Official Page"));
Assertions.assertNotNull(element);
Assertions.assertEquals("https://www.selenium.dev/", element.getAttribute("href"));
}
@Test
public void testPartialLinkText() {
WebElement element = driver.findElement(By.partialLinkText("Official Page"));
Assertions.assertNotNull(element);
Assertions.assertEquals("https://www.selenium.dev/", element.getAttribute("href"));
}
@Test
public void testTagName() {
WebElement element = driver.findElement(By.tagName("a"));
Assertions.assertNotNull(element);
Assertions.assertEquals("https://www.selenium.dev/", element.getAttribute("href"));
}
@Test
public void testXpath() {
WebElement element = driver.findElement(By.xpath("//input[@value='f']"));
Assertions.assertNotNull(element);
Assertions.assertEquals("radio", element.getAttribute("type"));
}
@Test
public void testByAll() {
driver.get("https://www.selenium.dev/selenium/web/login.html");
By locator = new ByAll(By.id("password-field"), By.id("username-field"));
List<WebElement> loginInputs = driver.findElements(locator);
Assertions.assertEquals(2, loginInputs.size());
}
@Test
public void testByChained() {
driver.get("https://www.selenium.dev/selenium/web/login.html");
By locator = new ByChained(By.id("login-form"), By.tagName("input"));
WebElement usernameInput = driver.findElement(locator);
Assertions.assertEquals("Username", usernameInput.getAttribute("placeholder"));
}
}
driver = webdriver.Chrome()
driver.get("https://www.selenium.dev/selenium/web/locators_tests/locators.html")
element = driver.find_element(By.LINK_TEXT, "Selenium Official Page")/examples/python/tests/elements/test_locators.py
import pytest
from selenium import webdriver
from selenium.webdriver.common.by import By
def test_class_name():
driver = webdriver.Chrome()
driver.get("https://www.selenium.dev/selenium/web/locators_tests/locators.html")
element = driver.find_element(By.CLASS_NAME, "information")
assert element is not None
assert element.tag_name == "input"
driver.quit()
def test_css_selector(driver):
driver = webdriver.Chrome()
driver.get("https://www.selenium.dev/selenium/web/locators_tests/locators.html")
element = driver.find_element(By.CSS_SELECTOR, "#fname")
assert element is not None
assert element.get_attribute("value") == "Jane"
driver.quit()
def test_id(driver):
driver = webdriver.Chrome()
driver.get("https://www.selenium.dev/selenium/web/locators_tests/locators.html")
element = driver.find_element(By.ID, "lname")
assert element is not None
assert element.get_attribute("value") == "Doe"
driver.quit()
def test_name(driver):
driver = webdriver.Chrome()
driver.get("https://www.selenium.dev/selenium/web/locators_tests/locators.html")
element = driver.find_element(By.NAME, "newsletter")
assert element is not None
assert element.tag_name == "input"
driver.quit()
def test_link_text(driver):
driver = webdriver.Chrome()
driver.get("https://www.selenium.dev/selenium/web/locators_tests/locators.html")
element = driver.find_element(By.LINK_TEXT, "Selenium Official Page")
assert element is not None
assert element.get_attribute("href") == "https://www.selenium.dev/"
driver.quit()
def test_partial_link_text(driver):
driver = webdriver.Chrome()
driver.get("https://www.selenium.dev/selenium/web/locators_tests/locators.html")
element = driver.find_element(By.PARTIAL_LINK_TEXT, "Official Page")
assert element is not None
assert element.get_attribute("href") == "https://www.selenium.dev/"
driver.quit()
def test_tag_name(driver):
driver = webdriver.Chrome()
driver.get("https://www.selenium.dev/selenium/web/locators_tests/locators.html")
element = driver.find_element(By.TAG_NAME, "a")
assert element is not None
assert element.get_attribute("href") == "https://www.selenium.dev/"
driver.quit()
def test_xpath(driver):
driver = webdriver.Chrome()
driver.get("https://www.selenium.dev/selenium/web/locators_tests/locators.html")
element = driver.find_element(By.XPATH, "//input[@value='f']")
assert element is not None
assert element.get_attribute("type") == "radio"
driver.quit()
var driver = new ChromeDriver();
driver.FindElement(By.LinkText("Selenium Official Page"));
driver.find_element(link_text: 'Selenium Official Page')/examples/ruby/spec/elements/locators_spec.rb
# frozen_string_literal: true
require 'spec_helper'
RSpec.describe 'Element Locators', skip: 'These are reference following the documentation example' do
it 'finds element by class name' do
driver.find_element(class: 'information')
end
it 'finds element by css selector' do
driver.find_element(css: '#fname')
end
it 'finds element by id' do
driver.find_element(id: 'lname')
end
it 'find element by name' do
driver.find_element(name: 'newsletter')
end
it 'finds element by link text' do
driver.find_element(link_text: 'Selenium Official Page')
end
it 'finds element by partial link text' do
driver.find_element(partial_link_text: 'Official Page')
end
it 'finds element by tag name' do
driver.find_element(tag_name: 'a')
end
it 'finds element by xpath' do
driver.find_element(xpath: "//input[@value='f']")
end
context 'with relative locators' do
it 'finds element above' do
driver.find_element({relative: {tag_name: 'input', above: {id: 'password'}}})
end
it 'finds element below' do
driver.find_element({relative: {tag_name: 'input', below: {id: 'email'}}})
end
it 'finds element to the left' do
driver.find_element({relative: {tag_name: 'button', left: {id: 'submit'}}})
end
it 'finds element to the right' do
driver.find_element({relative: {tag_name: 'button', right: {id: 'cancel'}}})
end
it 'finds near element' do
driver.find_element({relative: {tag_name: 'input', near: {id: 'lbl-email'}}})
end
it 'chains relative locators' do
driver.find_element({relative: {tag_name: 'button', below: {id: 'email'}, right: {id: 'cancel'}}})
end
end
end
let driver = await new Builder().forBrowser('chrome').build();
const loc = await driver.findElement(By.linkText('Selenium Official Page'));
val driver = ChromeDriver()
val loc: WebElement = driver.findElement(By.linkText("Selenium Official Page"))
partial link text
If the element we want to locate is a link, we can use the partial link text locator to identify it on the web page. The link text is the text displayed of the link. We can pass partial text as value. In the HTML snippet shared, we have a link available, lets see how will we locate it.
WebElement element = driver.findElement(By.partialLinkText("Official Page"));/examples/java/src/test/java/dev/selenium/elements/LocatorTest.java
import java.util.List;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.support.pagefactory.ByAll;
import org.openqa.selenium.support.pagefactory.ByChained;
public class LocatorTest {
private WebDriver driver;
@BeforeEach
public void setUp() {
// Initialize the driver before each test
driver = new ChromeDriver();
driver.get("https://www.selenium.dev/selenium/web/locators_tests/locators.html");
}
@AfterEach
public void tearDown() {
// Close the browser after each test
if (driver != null) {
driver.quit();
}
}
@Test
public void testClassName() {
WebElement element = driver.findElement(By.className("information"));
Assertions.assertNotNull(element);
Assertions.assertEquals("input", element.getTagName());
}
@Test
public void testCssSelector() {
WebElement element = driver.findElement(By.cssSelector("#fname"));
Assertions.assertNotNull(element);
Assertions.assertEquals("Jane", element.getAttribute("value"));
}
@Test
public void testId() {
WebElement element = driver.findElement(By.id("lname"));
Assertions.assertNotNull(element);
Assertions.assertEquals("Doe", element.getAttribute("value"));
}
@Test
public void testName() {
WebElement element = driver.findElement(By.name("newsletter"));
Assertions.assertNotNull(element);
Assertions.assertEquals("input", element.getTagName());
}
@Test
public void testLinkText() {
WebElement element = driver.findElement(By.linkText("Selenium Official Page"));
Assertions.assertNotNull(element);
Assertions.assertEquals("https://www.selenium.dev/", element.getAttribute("href"));
}
@Test
public void testPartialLinkText() {
WebElement element = driver.findElement(By.partialLinkText("Official Page"));
Assertions.assertNotNull(element);
Assertions.assertEquals("https://www.selenium.dev/", element.getAttribute("href"));
}
@Test
public void testTagName() {
WebElement element = driver.findElement(By.tagName("a"));
Assertions.assertNotNull(element);
Assertions.assertEquals("https://www.selenium.dev/", element.getAttribute("href"));
}
@Test
public void testXpath() {
WebElement element = driver.findElement(By.xpath("//input[@value='f']"));
Assertions.assertNotNull(element);
Assertions.assertEquals("radio", element.getAttribute("type"));
}
@Test
public void testByAll() {
driver.get("https://www.selenium.dev/selenium/web/login.html");
By locator = new ByAll(By.id("password-field"), By.id("username-field"));
List<WebElement> loginInputs = driver.findElements(locator);
Assertions.assertEquals(2, loginInputs.size());
}
@Test
public void testByChained() {
driver.get("https://www.selenium.dev/selenium/web/login.html");
By locator = new ByChained(By.id("login-form"), By.tagName("input"));
WebElement usernameInput = driver.findElement(locator);
Assertions.assertEquals("Username", usernameInput.getAttribute("placeholder"));
}
}
driver = webdriver.Chrome()
driver.get("https://www.selenium.dev/selenium/web/locators_tests/locators.html")
element = driver.find_element(By.PARTIAL_LINK_TEXT, "Official Page")/examples/python/tests/elements/test_locators.py
import pytest
from selenium import webdriver
from selenium.webdriver.common.by import By
def test_class_name():
driver = webdriver.Chrome()
driver.get("https://www.selenium.dev/selenium/web/locators_tests/locators.html")
element = driver.find_element(By.CLASS_NAME, "information")
assert element is not None
assert element.tag_name == "input"
driver.quit()
def test_css_selector(driver):
driver = webdriver.Chrome()
driver.get("https://www.selenium.dev/selenium/web/locators_tests/locators.html")
element = driver.find_element(By.CSS_SELECTOR, "#fname")
assert element is not None
assert element.get_attribute("value") == "Jane"
driver.quit()
def test_id(driver):
driver = webdriver.Chrome()
driver.get("https://www.selenium.dev/selenium/web/locators_tests/locators.html")
element = driver.find_element(By.ID, "lname")
assert element is not None
assert element.get_attribute("value") == "Doe"
driver.quit()
def test_name(driver):
driver = webdriver.Chrome()
driver.get("https://www.selenium.dev/selenium/web/locators_tests/locators.html")
element = driver.find_element(By.NAME, "newsletter")
assert element is not None
assert element.tag_name == "input"
driver.quit()
def test_link_text(driver):
driver = webdriver.Chrome()
driver.get("https://www.selenium.dev/selenium/web/locators_tests/locators.html")
element = driver.find_element(By.LINK_TEXT, "Selenium Official Page")
assert element is not None
assert element.get_attribute("href") == "https://www.selenium.dev/"
driver.quit()
def test_partial_link_text(driver):
driver = webdriver.Chrome()
driver.get("https://www.selenium.dev/selenium/web/locators_tests/locators.html")
element = driver.find_element(By.PARTIAL_LINK_TEXT, "Official Page")
assert element is not None
assert element.get_attribute("href") == "https://www.selenium.dev/"
driver.quit()
def test_tag_name(driver):
driver = webdriver.Chrome()
driver.get("https://www.selenium.dev/selenium/web/locators_tests/locators.html")
element = driver.find_element(By.TAG_NAME, "a")
assert element is not None
assert element.get_attribute("href") == "https://www.selenium.dev/"
driver.quit()
def test_xpath(driver):
driver = webdriver.Chrome()
driver.get("https://www.selenium.dev/selenium/web/locators_tests/locators.html")
element = driver.find_element(By.XPATH, "//input[@value='f']")
assert element is not None
assert element.get_attribute("type") == "radio"
driver.quit()
var driver = new ChromeDriver();
driver.FindElement(By.PartialLinkText("Official Page"));
driver.find_element(partial_link_text: 'Official Page')/examples/ruby/spec/elements/locators_spec.rb
# frozen_string_literal: true
require 'spec_helper'
RSpec.describe 'Element Locators', skip: 'These are reference following the documentation example' do
it 'finds element by class name' do
driver.find_element(class: 'information')
end
it 'finds element by css selector' do
driver.find_element(css: '#fname')
end
it 'finds element by id' do
driver.find_element(id: 'lname')
end
it 'find element by name' do
driver.find_element(name: 'newsletter')
end
it 'finds element by link text' do
driver.find_element(link_text: 'Selenium Official Page')
end
it 'finds element by partial link text' do
driver.find_element(partial_link_text: 'Official Page')
end
it 'finds element by tag name' do
driver.find_element(tag_name: 'a')
end
it 'finds element by xpath' do
driver.find_element(xpath: "//input[@value='f']")
end
context 'with relative locators' do
it 'finds element above' do
driver.find_element({relative: {tag_name: 'input', above: {id: 'password'}}})
end
it 'finds element below' do
driver.find_element({relative: {tag_name: 'input', below: {id: 'email'}}})
end
it 'finds element to the left' do
driver.find_element({relative: {tag_name: 'button', left: {id: 'submit'}}})
end
it 'finds element to the right' do
driver.find_element({relative: {tag_name: 'button', right: {id: 'cancel'}}})
end
it 'finds near element' do
driver.find_element({relative: {tag_name: 'input', near: {id: 'lbl-email'}}})
end
it 'chains relative locators' do
driver.find_element({relative: {tag_name: 'button', below: {id: 'email'}, right: {id: 'cancel'}}})
end
end
end
let driver = await new Builder().forBrowser('chrome').build();
const loc = await driver.findElement(By.partialLinkText('Official Page'));
val driver = ChromeDriver()
val loc: WebElement = driver.findElement(By.partialLinkText("Official Page"))
tag name
We can use the HTML TAG itself as a locator to identify the web element on the page. From the above HTML snippet shared, lets identify the link, using its html tag “a”.
WebElement element = driver.findElement(By.tagName("a"));/examples/java/src/test/java/dev/selenium/elements/LocatorTest.java
import java.util.List;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.support.pagefactory.ByAll;
import org.openqa.selenium.support.pagefactory.ByChained;
public class LocatorTest {
private WebDriver driver;
@BeforeEach
public void setUp() {
// Initialize the driver before each test
driver = new ChromeDriver();
driver.get("https://www.selenium.dev/selenium/web/locators_tests/locators.html");
}
@AfterEach
public void tearDown() {
// Close the browser after each test
if (driver != null) {
driver.quit();
}
}
@Test
public void testClassName() {
WebElement element = driver.findElement(By.className("information"));
Assertions.assertNotNull(element);
Assertions.assertEquals("input", element.getTagName());
}
@Test
public void testCssSelector() {
WebElement element = driver.findElement(By.cssSelector("#fname"));
Assertions.assertNotNull(element);
Assertions.assertEquals("Jane", element.getAttribute("value"));
}
@Test
public void testId() {
WebElement element = driver.findElement(By.id("lname"));
Assertions.assertNotNull(element);
Assertions.assertEquals("Doe", element.getAttribute("value"));
}
@Test
public void testName() {
WebElement element = driver.findElement(By.name("newsletter"));
Assertions.assertNotNull(element);
Assertions.assertEquals("input", element.getTagName());
}
@Test
public void testLinkText() {
WebElement element = driver.findElement(By.linkText("Selenium Official Page"));
Assertions.assertNotNull(element);
Assertions.assertEquals("https://www.selenium.dev/", element.getAttribute("href"));
}
@Test
public void testPartialLinkText() {
WebElement element = driver.findElement(By.partialLinkText("Official Page"));
Assertions.assertNotNull(element);
Assertions.assertEquals("https://www.selenium.dev/", element.getAttribute("href"));
}
@Test
public void testTagName() {
WebElement element = driver.findElement(By.tagName("a"));
Assertions.assertNotNull(element);
Assertions.assertEquals("https://www.selenium.dev/", element.getAttribute("href"));
}
@Test
public void testXpath() {
WebElement element = driver.findElement(By.xpath("//input[@value='f']"));
Assertions.assertNotNull(element);
Assertions.assertEquals("radio", element.getAttribute("type"));
}
@Test
public void testByAll() {
driver.get("https://www.selenium.dev/selenium/web/login.html");
By locator = new ByAll(By.id("password-field"), By.id("username-field"));
List<WebElement> loginInputs = driver.findElements(locator);
Assertions.assertEquals(2, loginInputs.size());
}
@Test
public void testByChained() {
driver.get("https://www.selenium.dev/selenium/web/login.html");
By locator = new ByChained(By.id("login-form"), By.tagName("input"));
WebElement usernameInput = driver.findElement(locator);
Assertions.assertEquals("Username", usernameInput.getAttribute("placeholder"));
}
}
driver = webdriver.Chrome()
driver.get("https://www.selenium.dev/selenium/web/locators_tests/locators.html")
element = driver.find_element(By.TAG_NAME, "a")/examples/python/tests/elements/test_locators.py
import pytest
from selenium import webdriver
from selenium.webdriver.common.by import By
def test_class_name():
driver = webdriver.Chrome()
driver.get("https://www.selenium.dev/selenium/web/locators_tests/locators.html")
element = driver.find_element(By.CLASS_NAME, "information")
assert element is not None
assert element.tag_name == "input"
driver.quit()
def test_css_selector(driver):
driver = webdriver.Chrome()
driver.get("https://www.selenium.dev/selenium/web/locators_tests/locators.html")
element = driver.find_element(By.CSS_SELECTOR, "#fname")
assert element is not None
assert element.get_attribute("value") == "Jane"
driver.quit()
def test_id(driver):
driver = webdriver.Chrome()
driver.get("https://www.selenium.dev/selenium/web/locators_tests/locators.html")
element = driver.find_element(By.ID, "lname")
assert element is not None
assert element.get_attribute("value") == "Doe"
driver.quit()
def test_name(driver):
driver = webdriver.Chrome()
driver.get("https://www.selenium.dev/selenium/web/locators_tests/locators.html")
element = driver.find_element(By.NAME, "newsletter")
assert element is not None
assert element.tag_name == "input"
driver.quit()
def test_link_text(driver):
driver = webdriver.Chrome()
driver.get("https://www.selenium.dev/selenium/web/locators_tests/locators.html")
element = driver.find_element(By.LINK_TEXT, "Selenium Official Page")
assert element is not None
assert element.get_attribute("href") == "https://www.selenium.dev/"
driver.quit()
def test_partial_link_text(driver):
driver = webdriver.Chrome()
driver.get("https://www.selenium.dev/selenium/web/locators_tests/locators.html")
element = driver.find_element(By.PARTIAL_LINK_TEXT, "Official Page")
assert element is not None
assert element.get_attribute("href") == "https://www.selenium.dev/"
driver.quit()
def test_tag_name(driver):
driver = webdriver.Chrome()
driver.get("https://www.selenium.dev/selenium/web/locators_tests/locators.html")
element = driver.find_element(By.TAG_NAME, "a")
assert element is not None
assert element.get_attribute("href") == "https://www.selenium.dev/"
driver.quit()
def test_xpath(driver):
driver = webdriver.Chrome()
driver.get("https://www.selenium.dev/selenium/web/locators_tests/locators.html")
element = driver.find_element(By.XPATH, "//input[@value='f']")
assert element is not None
assert element.get_attribute("type") == "radio"
driver.quit()
var driver = new ChromeDriver();
driver.FindElement(By.TagName("a"));
driver.find_element(tag_name: 'a')/examples/ruby/spec/elements/locators_spec.rb
# frozen_string_literal: true
require 'spec_helper'
RSpec.describe 'Element Locators', skip: 'These are reference following the documentation example' do
it 'finds element by class name' do
driver.find_element(class: 'information')
end
it 'finds element by css selector' do
driver.find_element(css: '#fname')
end
it 'finds element by id' do
driver.find_element(id: 'lname')
end
it 'find element by name' do
driver.find_element(name: 'newsletter')
end
it 'finds element by link text' do
driver.find_element(link_text: 'Selenium Official Page')
end
it 'finds element by partial link text' do
driver.find_element(partial_link_text: 'Official Page')
end
it 'finds element by tag name' do
driver.find_element(tag_name: 'a')
end
it 'finds element by xpath' do
driver.find_element(xpath: "//input[@value='f']")
end
context 'with relative locators' do
it 'finds element above' do
driver.find_element({relative: {tag_name: 'input', above: {id: 'password'}}})
end
it 'finds element below' do
driver.find_element({relative: {tag_name: 'input', below: {id: 'email'}}})
end
it 'finds element to the left' do
driver.find_element({relative: {tag_name: 'button', left: {id: 'submit'}}})
end
it 'finds element to the right' do
driver.find_element({relative: {tag_name: 'button', right: {id: 'cancel'}}})
end
it 'finds near element' do
driver.find_element({relative: {tag_name: 'input', near: {id: 'lbl-email'}}})
end
it 'chains relative locators' do
driver.find_element({relative: {tag_name: 'button', below: {id: 'email'}, right: {id: 'cancel'}}})
end
end
end
let driver = await new Builder().forBrowser('chrome').build();
const loc = await driver.findElement(By.tagName('a'));
val driver = ChromeDriver()
val loc: WebElement = driver.findElement(By.tagName("a"))
xpath
A HTML document can be considered as a XML document, and then we can use xpath which will be the path traversed to reach the element of interest to locate the element. The XPath could be absolute xpath, which is created from the root of the document. Example - /html/form/input[1]. This will return the male radio button. Or the xpath could be relative. Example- //input[@name=‘fname’]. This will return the first name text box. Let us create locator for female radio button using xpath.
WebElement element = driver.findElement(By.xpath("//input[@value='f']"));/examples/java/src/test/java/dev/selenium/elements/LocatorTest.java
import java.util.List;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.support.pagefactory.ByAll;
import org.openqa.selenium.support.pagefactory.ByChained;
public class LocatorTest {
private WebDriver driver;
@BeforeEach
public void setUp() {
// Initialize the driver before each test
driver = new ChromeDriver();
driver.get("https://www.selenium.dev/selenium/web/locators_tests/locators.html");
}
@AfterEach
public void tearDown() {
// Close the browser after each test
if (driver != null) {
driver.quit();
}
}
@Test
public void testClassName() {
WebElement element = driver.findElement(By.className("information"));
Assertions.assertNotNull(element);
Assertions.assertEquals("input", element.getTagName());
}
@Test
public void testCssSelector() {
WebElement element = driver.findElement(By.cssSelector("#fname"));
Assertions.assertNotNull(element);
Assertions.assertEquals("Jane", element.getAttribute("value"));
}
@Test
public void testId() {
WebElement element = driver.findElement(By.id("lname"));
Assertions.assertNotNull(element);
Assertions.assertEquals("Doe", element.getAttribute("value"));
}
@Test
public void testName() {
WebElement element = driver.findElement(By.name("newsletter"));
Assertions.assertNotNull(element);
Assertions.assertEquals("input", element.getTagName());
}
@Test
public void testLinkText() {
WebElement element = driver.findElement(By.linkText("Selenium Official Page"));
Assertions.assertNotNull(element);
Assertions.assertEquals("https://www.selenium.dev/", element.getAttribute("href"));
}
@Test
public void testPartialLinkText() {
WebElement element = driver.findElement(By.partialLinkText("Official Page"));
Assertions.assertNotNull(element);
Assertions.assertEquals("https://www.selenium.dev/", element.getAttribute("href"));
}
@Test
public void testTagName() {
WebElement element = driver.findElement(By.tagName("a"));
Assertions.assertNotNull(element);
Assertions.assertEquals("https://www.selenium.dev/", element.getAttribute("href"));
}
@Test
public void testXpath() {
WebElement element = driver.findElement(By.xpath("//input[@value='f']"));
Assertions.assertNotNull(element);
Assertions.assertEquals("radio", element.getAttribute("type"));
}
@Test
public void testByAll() {
driver.get("https://www.selenium.dev/selenium/web/login.html");
By locator = new ByAll(By.id("password-field"), By.id("username-field"));
List<WebElement> loginInputs = driver.findElements(locator);
Assertions.assertEquals(2, loginInputs.size());
}
@Test
public void testByChained() {
driver.get("https://www.selenium.dev/selenium/web/login.html");
By locator = new ByChained(By.id("login-form"), By.tagName("input"));
WebElement usernameInput = driver.findElement(locator);
Assertions.assertEquals("Username", usernameInput.getAttribute("placeholder"));
}
}
driver = webdriver.Chrome()
driver.get("https://www.selenium.dev/selenium/web/locators_tests/locators.html")
element = driver.find_element(By.XPATH, "//input[@value='f']")/examples/python/tests/elements/test_locators.py
import pytest
from selenium import webdriver
from selenium.webdriver.common.by import By
def test_class_name():
driver = webdriver.Chrome()
driver.get("https://www.selenium.dev/selenium/web/locators_tests/locators.html")
element = driver.find_element(By.CLASS_NAME, "information")
assert element is not None
assert element.tag_name == "input"
driver.quit()
def test_css_selector(driver):
driver = webdriver.Chrome()
driver.get("https://www.selenium.dev/selenium/web/locators_tests/locators.html")
element = driver.find_element(By.CSS_SELECTOR, "#fname")
assert element is not None
assert element.get_attribute("value") == "Jane"
driver.quit()
def test_id(driver):
driver = webdriver.Chrome()
driver.get("https://www.selenium.dev/selenium/web/locators_tests/locators.html")
element = driver.find_element(By.ID, "lname")
assert element is not None
assert element.get_attribute("value") == "Doe"
driver.quit()
def test_name(driver):
driver = webdriver.Chrome()
driver.get("https://www.selenium.dev/selenium/web/locators_tests/locators.html")
element = driver.find_element(By.NAME, "newsletter")
assert element is not None
assert element.tag_name == "input"
driver.quit()
def test_link_text(driver):
driver = webdriver.Chrome()
driver.get("https://www.selenium.dev/selenium/web/locators_tests/locators.html")
element = driver.find_element(By.LINK_TEXT, "Selenium Official Page")
assert element is not None
assert element.get_attribute("href") == "https://www.selenium.dev/"
driver.quit()
def test_partial_link_text(driver):
driver = webdriver.Chrome()
driver.get("https://www.selenium.dev/selenium/web/locators_tests/locators.html")
element = driver.find_element(By.PARTIAL_LINK_TEXT, "Official Page")
assert element is not None
assert element.get_attribute("href") == "https://www.selenium.dev/"
driver.quit()
def test_tag_name(driver):
driver = webdriver.Chrome()
driver.get("https://www.selenium.dev/selenium/web/locators_tests/locators.html")
element = driver.find_element(By.TAG_NAME, "a")
assert element is not None
assert element.get_attribute("href") == "https://www.selenium.dev/"
driver.quit()
def test_xpath(driver):
driver = webdriver.Chrome()
driver.get("https://www.selenium.dev/selenium/web/locators_tests/locators.html")
element = driver.find_element(By.XPATH, "//input[@value='f']")
assert element is not None
assert element.get_attribute("type") == "radio"
driver.quit()
var driver = new ChromeDriver();
driver.FindElement(By.Xpath("//input[@value='f']"));
driver.find_element(xpath: "//input[@value='f']")/examples/ruby/spec/elements/locators_spec.rb
# frozen_string_literal: true
require 'spec_helper'
RSpec.describe 'Element Locators', skip: 'These are reference following the documentation example' do
it 'finds element by class name' do
driver.find_element(class: 'information')
end
it 'finds element by css selector' do
driver.find_element(css: '#fname')
end
it 'finds element by id' do
driver.find_element(id: 'lname')
end
it 'find element by name' do
driver.find_element(name: 'newsletter')
end
it 'finds element by link text' do
driver.find_element(link_text: 'Selenium Official Page')
end
it 'finds element by partial link text' do
driver.find_element(partial_link_text: 'Official Page')
end
it 'finds element by tag name' do
driver.find_element(tag_name: 'a')
end
it 'finds element by xpath' do
driver.find_element(xpath: "//input[@value='f']")
end
context 'with relative locators' do
it 'finds element above' do
driver.find_element({relative: {tag_name: 'input', above: {id: 'password'}}})
end
it 'finds element below' do
driver.find_element({relative: {tag_name: 'input', below: {id: 'email'}}})
end
it 'finds element to the left' do
driver.find_element({relative: {tag_name: 'button', left: {id: 'submit'}}})
end
it 'finds element to the right' do
driver.find_element({relative: {tag_name: 'button', right: {id: 'cancel'}}})
end
it 'finds near element' do
driver.find_element({relative: {tag_name: 'input', near: {id: 'lbl-email'}}})
end
it 'chains relative locators' do
driver.find_element({relative: {tag_name: 'button', below: {id: 'email'}, right: {id: 'cancel'}}})
end
end
end
let driver = await new Builder().forBrowser('chrome').build();
const loc = await driver.findElement(By.xpath('//input[@value='f']'));
val driver = ChromeDriver()
val loc: WebElement = driver.findElement(By.xpath('//input[@value='f']'))
Utilizing Locators
The FindElement makes using locators a breeze! For most languages,
all you need to do is utilize webdriver.common.by.By, however in
others it’s as simple as setting a parameter in the FindElement function
By
import org.openqa.selenium.By;
WebDriver driver = new ChromeDriver();
driver.findElement(By.className("information"));
from selenium.webdriver.common.by import By
driver = webdriver.Chrome()
driver.find_element(By.CLASS_NAME, "information")
var driver = new ChromeDriver();
driver.FindElement(By.ClassName("information"));
driver.find_element(class: 'information')/examples/ruby/spec/elements/locators_spec.rb
# frozen_string_literal: true
require 'spec_helper'
RSpec.describe 'Element Locators', skip: 'These are reference following the documentation example' do
it 'finds element by class name' do
driver.find_element(class: 'information')
end
it 'finds element by css selector' do
driver.find_element(css: '#fname')
end
it 'finds element by id' do
driver.find_element(id: 'lname')
end
it 'find element by name' do
driver.find_element(name: 'newsletter')
end
it 'finds element by link text' do
driver.find_element(link_text: 'Selenium Official Page')
end
it 'finds element by partial link text' do
driver.find_element(partial_link_text: 'Official Page')
end
it 'finds element by tag name' do
driver.find_element(tag_name: 'a')
end
it 'finds element by xpath' do
driver.find_element(xpath: "//input[@value='f']")
end
context 'with relative locators' do
it 'finds element above' do
driver.find_element({relative: {tag_name: 'input', above: {id: 'password'}}})
end
it 'finds element below' do
driver.find_element({relative: {tag_name: 'input', below: {id: 'email'}}})
end
it 'finds element to the left' do
driver.find_element({relative: {tag_name: 'button', left: {id: 'submit'}}})
end
it 'finds element to the right' do
driver.find_element({relative: {tag_name: 'button', right: {id: 'cancel'}}})
end
it 'finds near element' do
driver.find_element({relative: {tag_name: 'input', near: {id: 'lbl-email'}}})
end
it 'chains relative locators' do
driver.find_element({relative: {tag_name: 'button', below: {id: 'email'}, right: {id: 'cancel'}}})
end
end
end
let driver = await new Builder().forBrowser('chrome').build();
const loc = await driver.findElement(By.className('information'));
import org.openqa.selenium.By
val driver = ChromeDriver()
val loc: WebElement = driver.findElement(By.className("information"))
ByChained
The ByChained class enables you to chain two By locators together. For example,
instead of having to locate a parent element, and then a child element of that parent,
you can instead combine those two FindElement functions into one.
By locator = new ByChained(By.id("login-form"), By.tagName("input"));
WebElement usernameInput = driver.findElement(locator);/examples/java/src/test/java/dev/selenium/elements/LocatorTest.java
import java.util.List;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.support.pagefactory.ByAll;
import org.openqa.selenium.support.pagefactory.ByChained;
public class LocatorTest {
private WebDriver driver;
@BeforeEach
public void setUp() {
// Initialize the driver before each test
driver = new ChromeDriver();
driver.get("https://www.selenium.dev/selenium/web/locators_tests/locators.html");
}
@AfterEach
public void tearDown() {
// Close the browser after each test
if (driver != null) {
driver.quit();
}
}
@Test
public void testClassName() {
WebElement element = driver.findElement(By.className("information"));
Assertions.assertNotNull(element);
Assertions.assertEquals("input", element.getTagName());
}
@Test
public void testCssSelector() {
WebElement element = driver.findElement(By.cssSelector("#fname"));
Assertions.assertNotNull(element);
Assertions.assertEquals("Jane", element.getAttribute("value"));
}
@Test
public void testId() {
WebElement element = driver.findElement(By.id("lname"));
Assertions.assertNotNull(element);
Assertions.assertEquals("Doe", element.getAttribute("value"));
}
@Test
public void testName() {
WebElement element = driver.findElement(By.name("newsletter"));
Assertions.assertNotNull(element);
Assertions.assertEquals("input", element.getTagName());
}
@Test
public void testLinkText() {
WebElement element = driver.findElement(By.linkText("Selenium Official Page"));
Assertions.assertNotNull(element);
Assertions.assertEquals("https://www.selenium.dev/", element.getAttribute("href"));
}
@Test
public void testPartialLinkText() {
WebElement element = driver.findElement(By.partialLinkText("Official Page"));
Assertions.assertNotNull(element);
Assertions.assertEquals("https://www.selenium.dev/", element.getAttribute("href"));
}
@Test
public void testTagName() {
WebElement element = driver.findElement(By.tagName("a"));
Assertions.assertNotNull(element);
Assertions.assertEquals("https://www.selenium.dev/", element.getAttribute("href"));
}
@Test
public void testXpath() {
WebElement element = driver.findElement(By.xpath("//input[@value='f']"));
Assertions.assertNotNull(element);
Assertions.assertEquals("radio", element.getAttribute("type"));
}
@Test
public void testByAll() {
driver.get("https://www.selenium.dev/selenium/web/login.html");
By locator = new ByAll(By.id("password-field"), By.id("username-field"));
List<WebElement> loginInputs = driver.findElements(locator);
Assertions.assertEquals(2, loginInputs.size());
}
@Test
public void testByChained() {
driver.get("https://www.selenium.dev/selenium/web/login.html");
By locator = new ByChained(By.id("login-form"), By.tagName("input"));
WebElement usernameInput = driver.findElement(locator);
Assertions.assertEquals("Username", usernameInput.getAttribute("placeholder"));
}
}
ByAll
The ByAll class enables you to utilize two By locators at once, finding elements that match either of your By locators.
For example, instead of having to utilize two FindElement() functions to find the username and password input fields
separately, you can instead find them together in one clean FindElements()
By locator = new ByAll(By.id("password-field"), By.id("username-field"));
List<WebElement> loginInputs = driver.findElements(locator);/examples/java/src/test/java/dev/selenium/elements/LocatorTest.java
import java.util.List;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.support.pagefactory.ByAll;
import org.openqa.selenium.support.pagefactory.ByChained;
public class LocatorTest {
private WebDriver driver;
@BeforeEach
public void setUp() {
// Initialize the driver before each test
driver = new ChromeDriver();
driver.get("https://www.selenium.dev/selenium/web/locators_tests/locators.html");
}
@AfterEach
public void tearDown() {
// Close the browser after each test
if (driver != null) {
driver.quit();
}
}
@Test
public void testClassName() {
WebElement element = driver.findElement(By.className("information"));
Assertions.assertNotNull(element);
Assertions.assertEquals("input", element.getTagName());
}
@Test
public void testCssSelector() {
WebElement element = driver.findElement(By.cssSelector("#fname"));
Assertions.assertNotNull(element);
Assertions.assertEquals("Jane", element.getAttribute("value"));
}
@Test
public void testId() {
WebElement element = driver.findElement(By.id("lname"));
Assertions.assertNotNull(element);
Assertions.assertEquals("Doe", element.getAttribute("value"));
}
@Test
public void testName() {
WebElement element = driver.findElement(By.name("newsletter"));
Assertions.assertNotNull(element);
Assertions.assertEquals("input", element.getTagName());
}
@Test
public void testLinkText() {
WebElement element = driver.findElement(By.linkText("Selenium Official Page"));
Assertions.assertNotNull(element);
Assertions.assertEquals("https://www.selenium.dev/", element.getAttribute("href"));
}
@Test
public void testPartialLinkText() {
WebElement element = driver.findElement(By.partialLinkText("Official Page"));
Assertions.assertNotNull(element);
Assertions.assertEquals("https://www.selenium.dev/", element.getAttribute("href"));
}
@Test
public void testTagName() {
WebElement element = driver.findElement(By.tagName("a"));
Assertions.assertNotNull(element);
Assertions.assertEquals("https://www.selenium.dev/", element.getAttribute("href"));
}
@Test
public void testXpath() {
WebElement element = driver.findElement(By.xpath("//input[@value='f']"));
Assertions.assertNotNull(element);
Assertions.assertEquals("radio", element.getAttribute("type"));
}
@Test
public void testByAll() {
driver.get("https://www.selenium.dev/selenium/web/login.html");
By locator = new ByAll(By.id("password-field"), By.id("username-field"));
List<WebElement> loginInputs = driver.findElements(locator);
Assertions.assertEquals(2, loginInputs.size());
}
@Test
public void testByChained() {
driver.get("https://www.selenium.dev/selenium/web/login.html");
By locator = new ByChained(By.id("login-form"), By.tagName("input"));
WebElement usernameInput = driver.findElement(locator);
Assertions.assertEquals("Username", usernameInput.getAttribute("placeholder"));
}
}
Relative Locators
Selenium 4 introduces Relative Locators (previously called as Friendly Locators). These locators are helpful when it is not easy to construct a locator for the desired element, but easy to describe spatially where the element is in relation to an element that does have an easily constructed locator.
How it works
Selenium uses the JavaScript function
getBoundingClientRect()
to determine the size and position of elements on the page, and can use this information to locate neighboring elements.
find the relative elements.
Relative locator methods can take as the argument for the point of origin, either a previously located element reference, or another locator. In these examples we’ll be using locators only, but you could swap the locator in the final method with an element object and it will work the same.
Let us consider the below example for understanding the relative locators.

Available relative locators
Above
If the email text field element is not easily identifiable for some reason, but the password text field element is, we can locate the text field element using the fact that it is an “input” element “above” the password element.
By emailLocator = RelativeLocator.with(By.tagName("input")).above(By.id("password"));email_locator = locate_with(By.TAG_NAME, "input").above({By.ID: "password"})var emailLocator = RelativeBy.WithLocator(By.TagName("input")).Above(By.Id("password")); driver.find_element({relative: {tag_name: 'input', above: {id: 'password'}}})/examples/ruby/spec/elements/locators_spec.rb
# frozen_string_literal: true
require 'spec_helper'
RSpec.describe 'Element Locators', skip: 'These are reference following the documentation example' do
it 'finds element by class name' do
driver.find_element(class: 'information')
end
it 'finds element by css selector' do
driver.find_element(css: '#fname')
end
it 'finds element by id' do
driver.find_element(id: 'lname')
end
it 'find element by name' do
driver.find_element(name: 'newsletter')
end
it 'finds element by link text' do
driver.find_element(link_text: 'Selenium Official Page')
end
it 'finds element by partial link text' do
driver.find_element(partial_link_text: 'Official Page')
end
it 'finds element by tag name' do
driver.find_element(tag_name: 'a')
end
it 'finds element by xpath' do
driver.find_element(xpath: "//input[@value='f']")
end
context 'with relative locators' do
it 'finds element above' do
driver.find_element({relative: {tag_name: 'input', above: {id: 'password'}}})
end
it 'finds element below' do
driver.find_element({relative: {tag_name: 'input', below: {id: 'email'}}})
end
it 'finds element to the left' do
driver.find_element({relative: {tag_name: 'button', left: {id: 'submit'}}})
end
it 'finds element to the right' do
driver.find_element({relative: {tag_name: 'button', right: {id: 'cancel'}}})
end
it 'finds near element' do
driver.find_element({relative: {tag_name: 'input', near: {id: 'lbl-email'}}})
end
it 'chains relative locators' do
driver.find_element({relative: {tag_name: 'button', below: {id: 'email'}, right: {id: 'cancel'}}})
end
end
end
let emailLocator = locateWith(By.tagName('input')).above(By.id('password'));val emailLocator = RelativeLocator.with(By.tagName("input")).above(By.id("password"))Below
If the password text field element is not easily identifiable for some reason, but the email text field element is, we can locate the text field element using the fact that it is an “input” element “below” the email element.
By passwordLocator = RelativeLocator.with(By.tagName("input")).below(By.id("email"));password_locator = locate_with(By.TAG_NAME, "input").below({By.ID: "email"})var passwordLocator = RelativeBy.WithLocator(By.TagName("input")).Below(By.Id("email")); driver.find_element({relative: {tag_name: 'input', below: {id: 'email'}}})/examples/ruby/spec/elements/locators_spec.rb
# frozen_string_literal: true
require 'spec_helper'
RSpec.describe 'Element Locators', skip: 'These are reference following the documentation example' do
it 'finds element by class name' do
driver.find_element(class: 'information')
end
it 'finds element by css selector' do
driver.find_element(css: '#fname')
end
it 'finds element by id' do
driver.find_element(id: 'lname')
end
it 'find element by name' do
driver.find_element(name: 'newsletter')
end
it 'finds element by link text' do
driver.find_element(link_text: 'Selenium Official Page')
end
it 'finds element by partial link text' do
driver.find_element(partial_link_text: 'Official Page')
end
it 'finds element by tag name' do
driver.find_element(tag_name: 'a')
end
it 'finds element by xpath' do
driver.find_element(xpath: "//input[@value='f']")
end
context 'with relative locators' do
it 'finds element above' do
driver.find_element({relative: {tag_name: 'input', above: {id: 'password'}}})
end
it 'finds element below' do
driver.find_element({relative: {tag_name: 'input', below: {id: 'email'}}})
end
it 'finds element to the left' do
driver.find_element({relative: {tag_name: 'button', left: {id: 'submit'}}})
end
it 'finds element to the right' do
driver.find_element({relative: {tag_name: 'button', right: {id: 'cancel'}}})
end
it 'finds near element' do
driver.find_element({relative: {tag_name: 'input', near: {id: 'lbl-email'}}})
end
it 'chains relative locators' do
driver.find_element({relative: {tag_name: 'button', below: {id: 'email'}, right: {id: 'cancel'}}})
end
end
end
let passwordLocator = locateWith(By.tagName('input')).below(By.id('email'));val passwordLocator = RelativeLocator.with(By.tagName("input")).below(By.id("email"))Left of
If the cancel button is not easily identifiable for some reason, but the submit button element is, we can locate the cancel button element using the fact that it is a “button” element to the “left of” the submit element.
By cancelLocator = RelativeLocator.with(By.tagName("button")).toLeftOf(By.id("submit"));cancel_locator = locate_with(By.TAG_NAME, "button").to_left_of({By.ID: "submit"})var cancelLocator = RelativeBy.WithLocator(By.tagName("button")).LeftOf(By.Id("submit")); driver.find_element({relative: {tag_name: 'button', left: {id: 'submit'}}})/examples/ruby/spec/elements/locators_spec.rb
# frozen_string_literal: true
require 'spec_helper'
RSpec.describe 'Element Locators', skip: 'These are reference following the documentation example' do
it 'finds element by class name' do
driver.find_element(class: 'information')
end
it 'finds element by css selector' do
driver.find_element(css: '#fname')
end
it 'finds element by id' do
driver.find_element(id: 'lname')
end
it 'find element by name' do
driver.find_element(name: 'newsletter')
end
it 'finds element by link text' do
driver.find_element(link_text: 'Selenium Official Page')
end
it 'finds element by partial link text' do
driver.find_element(partial_link_text: 'Official Page')
end
it 'finds element by tag name' do
driver.find_element(tag_name: 'a')
end
it 'finds element by xpath' do
driver.find_element(xpath: "//input[@value='f']")
end
context 'with relative locators' do
it 'finds element above' do
driver.find_element({relative: {tag_name: 'input', above: {id: 'password'}}})
end
it 'finds element below' do
driver.find_element({relative: {tag_name: 'input', below: {id: 'email'}}})
end
it 'finds element to the left' do
driver.find_element({relative: {tag_name: 'button', left: {id: 'submit'}}})
end
it 'finds element to the right' do
driver.find_element({relative: {tag_name: 'button', right: {id: 'cancel'}}})
end
it 'finds near element' do
driver.find_element({relative: {tag_name: 'input', near: {id: 'lbl-email'}}})
end
it 'chains relative locators' do
driver.find_element({relative: {tag_name: 'button', below: {id: 'email'}, right: {id: 'cancel'}}})
end
end
end
let cancelLocator = locateWith(By.tagName('button')).toLeftOf(By.id('submit'));val cancelLocator = RelativeLocator.with(By.tagName("button")).toLeftOf(By.id("submit"))Right of
If the submit button is not easily identifiable for some reason, but the cancel button element is, we can locate the submit button element using the fact that it is a “button” element “to the right of” the cancel element.
By submitLocator = RelativeLocator.with(By.tagName("button")).toRightOf(By.id("cancel"));submit_locator = locate_with(By.TAG_NAME, "button").to_right_of({By.ID: "cancel"})var submitLocator = RelativeBy.WithLocator(By.tagName("button")).RightOf(By.Id("cancel")); driver.find_element({relative: {tag_name: 'button', right: {id: 'cancel'}}})/examples/ruby/spec/elements/locators_spec.rb
# frozen_string_literal: true
require 'spec_helper'
RSpec.describe 'Element Locators', skip: 'These are reference following the documentation example' do
it 'finds element by class name' do
driver.find_element(class: 'information')
end
it 'finds element by css selector' do
driver.find_element(css: '#fname')
end
it 'finds element by id' do
driver.find_element(id: 'lname')
end
it 'find element by name' do
driver.find_element(name: 'newsletter')
end
it 'finds element by link text' do
driver.find_element(link_text: 'Selenium Official Page')
end
it 'finds element by partial link text' do
driver.find_element(partial_link_text: 'Official Page')
end
it 'finds element by tag name' do
driver.find_element(tag_name: 'a')
end
it 'finds element by xpath' do
driver.find_element(xpath: "//input[@value='f']")
end
context 'with relative locators' do
it 'finds element above' do
driver.find_element({relative: {tag_name: 'input', above: {id: 'password'}}})
end
it 'finds element below' do
driver.find_element({relative: {tag_name: 'input', below: {id: 'email'}}})
end
it 'finds element to the left' do
driver.find_element({relative: {tag_name: 'button', left: {id: 'submit'}}})
end
it 'finds element to the right' do
driver.find_element({relative: {tag_name: 'button', right: {id: 'cancel'}}})
end
it 'finds near element' do
driver.find_element({relative: {tag_name: 'input', near: {id: 'lbl-email'}}})
end
it 'chains relative locators' do
driver.find_element({relative: {tag_name: 'button', below: {id: 'email'}, right: {id: 'cancel'}}})
end
end
end
let submitLocator = locateWith(By.tagName('button')).toRightOf(By.id('cancel'));val submitLocator = RelativeLocator.with(By.tagName("button")).toRightOf(By.id("cancel"))Near
If the relative positioning is not obvious, or it varies based on window size, you can use the near method to
identify an element that is at most 50px away from the provided locator.
One great use case for this is to work with a form element that doesn’t have an easily constructed locator,
but its associated input label element does.
By emailLocator = RelativeLocator.with(By.tagName("input")).near(By.id("lbl-email"));email_locator = locate_with(By.TAG_NAME, "input").near({By.ID: "lbl-email"})var emailLocator = RelativeBy.WithLocator(By.tagName("input")).Near(By.Id("lbl-email")); driver.find_element({relative: {tag_name: 'input', near: {id: 'lbl-email'}}})/examples/ruby/spec/elements/locators_spec.rb
# frozen_string_literal: true
require 'spec_helper'
RSpec.describe 'Element Locators', skip: 'These are reference following the documentation example' do
it 'finds element by class name' do
driver.find_element(class: 'information')
end
it 'finds element by css selector' do
driver.find_element(css: '#fname')
end
it 'finds element by id' do
driver.find_element(id: 'lname')
end
it 'find element by name' do
driver.find_element(name: 'newsletter')
end
it 'finds element by link text' do
driver.find_element(link_text: 'Selenium Official Page')
end
it 'finds element by partial link text' do
driver.find_element(partial_link_text: 'Official Page')
end
it 'finds element by tag name' do
driver.find_element(tag_name: 'a')
end
it 'finds element by xpath' do
driver.find_element(xpath: "//input[@value='f']")
end
context 'with relative locators' do
it 'finds element above' do
driver.find_element({relative: {tag_name: 'input', above: {id: 'password'}}})
end
it 'finds element below' do
driver.find_element({relative: {tag_name: 'input', below: {id: 'email'}}})
end
it 'finds element to the left' do
driver.find_element({relative: {tag_name: 'button', left: {id: 'submit'}}})
end
it 'finds element to the right' do
driver.find_element({relative: {tag_name: 'button', right: {id: 'cancel'}}})
end
it 'finds near element' do
driver.find_element({relative: {tag_name: 'input', near: {id: 'lbl-email'}}})
end
it 'chains relative locators' do
driver.find_element({relative: {tag_name: 'button', below: {id: 'email'}, right: {id: 'cancel'}}})
end
end
end
let emailLocator = locateWith(By.tagName('input')).near(By.id('lbl-email'));val emailLocator = RelativeLocator.with(By.tagName("input")).near(By.id("lbl-email"));Chaining relative locators
You can also chain locators if needed. Sometimes the element is most easily identified as being both above/below one element and right/left of another.
By submitLocator = RelativeLocator.with(By.tagName("button")).below(By.id("email")).toRightOf(By.id("cancel"));submit_locator = locate_with(By.TAG_NAME, "button").below({By.ID: "email"}).to_right_of({By.ID: "cancel"})var submitLocator = RelativeBy.WithLocator(By.tagName("button")).Below(By.Id("email")).RightOf(By.Id("cancel")); driver.find_element({relative: {tag_name: 'button', below: {id: 'email'}, right: {id: 'cancel'}}})/examples/ruby/spec/elements/locators_spec.rb
# frozen_string_literal: true
require 'spec_helper'
RSpec.describe 'Element Locators', skip: 'These are reference following the documentation example' do
it 'finds element by class name' do
driver.find_element(class: 'information')
end
it 'finds element by css selector' do
driver.find_element(css: '#fname')
end
it 'finds element by id' do
driver.find_element(id: 'lname')
end
it 'find element by name' do
driver.find_element(name: 'newsletter')
end
it 'finds element by link text' do
driver.find_element(link_text: 'Selenium Official Page')
end
it 'finds element by partial link text' do
driver.find_element(partial_link_text: 'Official Page')
end
it 'finds element by tag name' do
driver.find_element(tag_name: 'a')
end
it 'finds element by xpath' do
driver.find_element(xpath: "//input[@value='f']")
end
context 'with relative locators' do
it 'finds element above' do
driver.find_element({relative: {tag_name: 'input', above: {id: 'password'}}})
end
it 'finds element below' do
driver.find_element({relative: {tag_name: 'input', below: {id: 'email'}}})
end
it 'finds element to the left' do
driver.find_element({relative: {tag_name: 'button', left: {id: 'submit'}}})
end
it 'finds element to the right' do
driver.find_element({relative: {tag_name: 'button', right: {id: 'cancel'}}})
end
it 'finds near element' do
driver.find_element({relative: {tag_name: 'input', near: {id: 'lbl-email'}}})
end
it 'chains relative locators' do
driver.find_element({relative: {tag_name: 'button', below: {id: 'email'}, right: {id: 'cancel'}}})
end
end
end
let submitLocator = locateWith(By.tagName('button')).below(By.id('email')).toRightOf(By.id('cancel'));val submitLocator = RelativeLocator.with(By.tagName("button")).below(By.id("email")).toRightOf(By.id("cancel"))4 - 关于网络元素的信息
您可以查询有关特定元素的许多详细信息。
是否显示
此方法用于检查连接的元素是否正确显示在网页上. 返回一个 Boolean 值,
如果连接的元素显示在当前的浏览器上下文中,则为True,否则返回false。
此功能于W3C规范中提及, 但由于无法覆盖所有潜在条件而无法定义。 因此,Selenium不能期望驱动程序直接实现这种功能,现在依赖于直接执行大量JavaScript函数。 这个函数对一个元素的性质和在树中的关系做了许多近似的判断,以返回一个值。
boolean isEmailVisible = driver.findElement(By.name("email_input")).isDisplayed();
assertTrue(isEmailVisible);
/examples/java/src/test/java/dev/selenium/elements/InformationTest.java
package dev.selenium.elements;
import org.junit.jupiter.api.Test;
import org.openqa.selenium.By;
import org.openqa.selenium.Rectangle;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import java.time.Duration;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
public class InformationTest {
@Test
public void informationWithElements() {
WebDriver driver = new ChromeDriver();
driver.manage().timeouts().implicitlyWait(Duration.ofMillis(500));
// Navigate to Url
driver.get("https://www.selenium.dev/selenium/web/inputs.html");
// isDisplayed
// Get boolean value for is element display
boolean isEmailVisible = driver.findElement(By.name("email_input")).isDisplayed();
assertTrue(isEmailVisible);
// isEnabled
// returns true if element is enabled
boolean isEnabledButton = driver.findElement(By.name("button_input")).isEnabled();
assertTrue(isEnabledButton);
// isSelected
// returns true if element is checked
boolean isSelectedCheck = driver.findElement(By.name("checkbox_input")).isSelected();
assertTrue(isSelectedCheck);
// TagName
// returns TagName of the element
String tagNameInp = driver.findElement(By.name("email_input")).getTagName();
assertEquals("input", tagNameInp);
// GetRect
// Returns height, width, x and y coordinates referenced element
Rectangle res = driver.findElement(By.name("range_input")).getRect();
// Rectangle class provides getX,getY, getWidth, getHeight methods
assertEquals(10, res.getX());
// Retrieves the computed style property 'font-size' of field
String cssValue = driver.findElement(By.name("color_input")).getCssValue("font-size");
assertEquals(cssValue, "13.3333px");
// GetText
// Retrieves the text of the element
String text = driver.findElement(By.tagName("h1")).getText();
assertEquals(text, "Testing Inputs");
// FetchAttributes
// identify the email text box
WebElement emailTxt = driver.findElement(By.name(("email_input")));
// fetch the value property associated with the textbox
String valueInfo = emailTxt.getAttribute("value");
assertEquals(valueInfo, "admin@localhost");
driver.quit();
}
}
driver.get("https://www.selenium.dev/selenium/web/inputs.html")
# isDisplayed
is_email_visible = driver.find_element(By.NAME, "email_input").is_displayed()/examples/python/tests/elements/test_information.py
from selenium import webdriver
from selenium.webdriver.common.by import By
import pytest
def test_informarion():
# Initialize WebDriver
driver = webdriver.Chrome()
driver.implicitly_wait(0.5)
driver.get("https://www.selenium.dev/selenium/web/inputs.html")
# isDisplayed
is_email_visible = driver.find_element(By.NAME, "email_input").is_displayed()
assert is_email_visible == True
# isEnabled
is_enabled_button = driver.find_element(By.NAME, "button_input").is_enabled()
assert is_enabled_button == True
# isSelected
is_selected_check = driver.find_element(By.NAME, "checkbox_input").is_selected()
assert is_selected_check == True
# TagName
tag_name_inp = driver.find_element(By.NAME, "email_input").tag_name
assert tag_name_inp == "input"
# GetRect
rect = driver.find_element(By.NAME, "range_input").rect
assert rect["x"] == 10
# CSS Value
css_value = driver.find_element(By.NAME, "color_input").value_of_css_property(
"font-size"
)
assert css_value == "13.3333px"
# GetText
text = driver.find_element(By.TAG_NAME, "h1").text
assert text == "Testing Inputs"
# FetchAttributes
email_txt = driver.find_element(By.NAME, "email_input")
value_info = email_txt.get_attribute("value")
assert value_info == "admin@localhost"
// Navigate to Url
driver.Url= "https://www.selenium.dev/selenium/web/inputs.html";
// isDisplayed
// Get boolean value for is element display
bool isEmailVisible = driver.FindElement(By.Name("email_input")).Displayed;/examples/dotnet/SeleniumDocs/Elements/InformationTest.cs
using System;
using System.Drawing;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using OpenQA.Selenium;
using OpenQA.Selenium.Chrome;
namespace SeleniumDocs.Elements
{
[TestClass]
public class InformationTest
{
[TestMethod]
public void TestInformationCommands(){
WebDriver driver = new ChromeDriver();
driver.Manage().Timeouts().ImplicitWait = TimeSpan.FromMilliseconds(500);
// Navigate to Url
driver.Url= "https://www.selenium.dev/selenium/web/inputs.html";
// isDisplayed
// Get boolean value for is element display
bool isEmailVisible = driver.FindElement(By.Name("email_input")).Displayed;
Assert.AreEqual(isEmailVisible, true);
// isEnabled
// returns true if element is enabled else returns false
bool isEnabledButton = driver.FindElement(By.Name("button_input")).Enabled;
Assert.AreEqual(isEnabledButton, true);
// isSelected
// returns true if element is checked else returns false
bool isSelectedCheck = driver.FindElement(By.Name("checkbox_input")).Selected;
Assert.AreEqual(isSelectedCheck, true);
// TagName
// returns TagName of the element
string tagNameInp = driver.FindElement(By.Name("email_input")).TagName;
Assert.AreEqual(tagNameInp, "input");
// Get Location and Size
// Get Location
IWebElement rangeElement = driver.FindElement(By.Name("range_input"));
Point point = rangeElement.Location;
Assert.IsNotNull(point.X);
// Get Size
int height=rangeElement.Size.Height;
Assert.IsNotNull(height);
// Retrieves the computed style property 'font-size' of field
string cssValue = driver.FindElement(By.Name("color_input")).GetCssValue("font-size");
Assert.AreEqual(cssValue, "13.3333px");
// GetText
// Retrieves the text of the element
string text = driver.FindElement(By.TagName("h1")).Text;
Assert.AreEqual(text, "Testing Inputs");
// FetchAttributes
// identify the email text box
IWebElement emailTxt = driver.FindElement(By.Name("email_input"));
// fetch the value property associated with the textbox
string valueInfo = emailTxt.GetAttribute("value");
Assert.AreEqual(valueInfo, "admin@localhost");
//Quit the driver
driver.Quit();
}
}
} displayed_value = driver.find_element(name: 'email_input').displayed?/examples/ruby/spec/elements/information_spec.rb
# frozen_string_literal: true
require 'spec_helper'
RSpec.describe 'Element Information' do
let(:driver) { start_session }
let(:url) { 'https://www.selenium.dev/selenium/web/inputs.html' }
before { driver.get(url) }
it 'checks if an element is displayed' do
displayed_value = driver.find_element(name: 'email_input').displayed?
expect(displayed_value).to be_truthy
end
it 'checks if an element is enabled' do
enabled_value = driver.find_element(name: 'email_input').enabled?
expect(enabled_value).to be_truthy
end
it 'checks if an element is selected' do
selected_value = driver.find_element(name: 'email_input').selected?
expect(selected_value).to be_falsey
end
it 'gets the tag name of an element' do
tag_name = driver.find_element(name: 'email_input').tag_name
expect(tag_name).not_to be_empty
end
it 'gets the size and position of an element' do
size = driver.find_element(name: 'email_input').size
expect(size.width).to be_positive
expect(size.height).to be_positive
end
it 'gets the css value of an element' do
css_value = driver.find_element(name: 'email_input').css_value('background-color')
expect(css_value).not_to be_empty
end
it 'gets the text of an element' do
text = driver.find_element(xpath: '//h1').text
expect(text).to eq('Testing Inputs')
end
it 'gets the attribute value of an element' do
attribute_value = driver.find_element(name: 'number_input').attribute('value')
expect(attribute_value).not_to be_empty
end
end
// Resolves Promise and returns boolean value
let result = await driver.findElement(By.name("email_input")).isDisplayed();/examples/javascript/test/elements/information.spec.js
const {By, Builder} = require('selenium-webdriver');
const assert = require("assert");
describe('Element Information Test', function () {
let driver;
before(async function () {
driver = await new Builder().forBrowser('chrome').build();
});
beforeEach(async ()=> {
await driver.get('https://www.selenium.dev/selenium/web/inputs.html');
})
it('Check if element is displayed', async function () {
// Resolves Promise and returns boolean value
let result = await driver.findElement(By.name("email_input")).isDisplayed();
assert.equal(result,true);
});
it('Check if button is enabled', async function () {
// Resolves Promise and returns boolean value
let element = await driver.findElement(By.name("button_input")).isEnabled();
assert.equal(element, true);
});
it('Check if checkbox is selected', async function () {
// Returns true if element is checked else returns false
let isSelected = await driver.findElement(By.name("checkbox_input")).isSelected();
assert.equal(isSelected, true);
});
it('Should return the tagname', async function () {
// Returns TagName of the element
let value = await driver.findElement(By.name('email_input')).getTagName();
assert.equal(value, "input");
});
it('Should be able to fetch element size and position ', async function () {
// Returns height, width, x and y position of the element
let object = await driver.findElement(By.name('range_input')).getRect();
assert.ok(object.height!==null)
assert.ok(object.width!==null)
assert.ok(object.y!==null)
assert.ok(object.x!==null)
});
it('Should be able to fetch attributes and properties ', async function () {
// identify the email text box
const emailElement = await driver.findElement(By.xpath('//input[@name="email_input"]'));
//fetch the attribute "name" associated with the textbox
const nameAttribute = await emailElement.getAttribute("name");
assert.equal(nameAttribute, "email_input")
});
after(async () => await driver.quit());
});
describe('Element Information Test', function () {
let driver;
before(async function () {
driver = await new Builder().forBrowser('chrome').build();
});
it('Should return the css specified CSS value', async function () {
await driver.get('https://www.selenium.dev/selenium/web/colorPage.html');
// Returns background color of the element
let value = await driver.findElement(By.id('namedColor')).getCssValue('background-color');
assert.equal(value, "rgba(0, 128, 0, 1)");
});
it('Should return the css specified CSS value', async function () {
await driver.get('https://www.selenium.dev/selenium/web/linked_image.html');
// Returns text of the element
let text = await driver.findElement(By.id('justanotherLink')).getText();
assert.equal(text, "Just another link.");
});
after(async () => await driver.quit());
});
//navigates to url
driver.get("https://www.selenium.dev/selenium/web/inputs.html")
//returns true if element is displayed else returns false
val flag = driver.findElement(By.name("email_input")).isDisplayed()是否启用
此方法用于检查所连接的元素在网页上是启用还是禁用状态。 返回一个布尔值,如果在当前浏览上下文中是 启用 状态,则返回 true,否则返回 false。
boolean isEnabledButton = driver.findElement(By.name("button_input")).isEnabled();
assertTrue(isEnabledButton);
/examples/java/src/test/java/dev/selenium/elements/InformationTest.java
package dev.selenium.elements;
import org.junit.jupiter.api.Test;
import org.openqa.selenium.By;
import org.openqa.selenium.Rectangle;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import java.time.Duration;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
public class InformationTest {
@Test
public void informationWithElements() {
WebDriver driver = new ChromeDriver();
driver.manage().timeouts().implicitlyWait(Duration.ofMillis(500));
// Navigate to Url
driver.get("https://www.selenium.dev/selenium/web/inputs.html");
// isDisplayed
// Get boolean value for is element display
boolean isEmailVisible = driver.findElement(By.name("email_input")).isDisplayed();
assertTrue(isEmailVisible);
// isEnabled
// returns true if element is enabled
boolean isEnabledButton = driver.findElement(By.name("button_input")).isEnabled();
assertTrue(isEnabledButton);
// isSelected
// returns true if element is checked
boolean isSelectedCheck = driver.findElement(By.name("checkbox_input")).isSelected();
assertTrue(isSelectedCheck);
// TagName
// returns TagName of the element
String tagNameInp = driver.findElement(By.name("email_input")).getTagName();
assertEquals("input", tagNameInp);
// GetRect
// Returns height, width, x and y coordinates referenced element
Rectangle res = driver.findElement(By.name("range_input")).getRect();
// Rectangle class provides getX,getY, getWidth, getHeight methods
assertEquals(10, res.getX());
// Retrieves the computed style property 'font-size' of field
String cssValue = driver.findElement(By.name("color_input")).getCssValue("font-size");
assertEquals(cssValue, "13.3333px");
// GetText
// Retrieves the text of the element
String text = driver.findElement(By.tagName("h1")).getText();
assertEquals(text, "Testing Inputs");
// FetchAttributes
// identify the email text box
WebElement emailTxt = driver.findElement(By.name(("email_input")));
// fetch the value property associated with the textbox
String valueInfo = emailTxt.getAttribute("value");
assertEquals(valueInfo, "admin@localhost");
driver.quit();
}
}
is_enabled_button = driver.find_element(By.NAME, "button_input").is_enabled()/examples/python/tests/elements/test_information.py
from selenium import webdriver
from selenium.webdriver.common.by import By
import pytest
def test_informarion():
# Initialize WebDriver
driver = webdriver.Chrome()
driver.implicitly_wait(0.5)
driver.get("https://www.selenium.dev/selenium/web/inputs.html")
# isDisplayed
is_email_visible = driver.find_element(By.NAME, "email_input").is_displayed()
assert is_email_visible == True
# isEnabled
is_enabled_button = driver.find_element(By.NAME, "button_input").is_enabled()
assert is_enabled_button == True
# isSelected
is_selected_check = driver.find_element(By.NAME, "checkbox_input").is_selected()
assert is_selected_check == True
# TagName
tag_name_inp = driver.find_element(By.NAME, "email_input").tag_name
assert tag_name_inp == "input"
# GetRect
rect = driver.find_element(By.NAME, "range_input").rect
assert rect["x"] == 10
# CSS Value
css_value = driver.find_element(By.NAME, "color_input").value_of_css_property(
"font-size"
)
assert css_value == "13.3333px"
# GetText
text = driver.find_element(By.TAG_NAME, "h1").text
assert text == "Testing Inputs"
# FetchAttributes
email_txt = driver.find_element(By.NAME, "email_input")
value_info = email_txt.get_attribute("value")
assert value_info == "admin@localhost"
// isEnabled
// returns true if element is enabled else returns false
bool isEnabledButton = driver.FindElement(By.Name("button_input")).Enabled;/examples/dotnet/SeleniumDocs/Elements/InformationTest.cs
using System;
using System.Drawing;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using OpenQA.Selenium;
using OpenQA.Selenium.Chrome;
namespace SeleniumDocs.Elements
{
[TestClass]
public class InformationTest
{
[TestMethod]
public void TestInformationCommands(){
WebDriver driver = new ChromeDriver();
driver.Manage().Timeouts().ImplicitWait = TimeSpan.FromMilliseconds(500);
// Navigate to Url
driver.Url= "https://www.selenium.dev/selenium/web/inputs.html";
// isDisplayed
// Get boolean value for is element display
bool isEmailVisible = driver.FindElement(By.Name("email_input")).Displayed;
Assert.AreEqual(isEmailVisible, true);
// isEnabled
// returns true if element is enabled else returns false
bool isEnabledButton = driver.FindElement(By.Name("button_input")).Enabled;
Assert.AreEqual(isEnabledButton, true);
// isSelected
// returns true if element is checked else returns false
bool isSelectedCheck = driver.FindElement(By.Name("checkbox_input")).Selected;
Assert.AreEqual(isSelectedCheck, true);
// TagName
// returns TagName of the element
string tagNameInp = driver.FindElement(By.Name("email_input")).TagName;
Assert.AreEqual(tagNameInp, "input");
// Get Location and Size
// Get Location
IWebElement rangeElement = driver.FindElement(By.Name("range_input"));
Point point = rangeElement.Location;
Assert.IsNotNull(point.X);
// Get Size
int height=rangeElement.Size.Height;
Assert.IsNotNull(height);
// Retrieves the computed style property 'font-size' of field
string cssValue = driver.FindElement(By.Name("color_input")).GetCssValue("font-size");
Assert.AreEqual(cssValue, "13.3333px");
// GetText
// Retrieves the text of the element
string text = driver.FindElement(By.TagName("h1")).Text;
Assert.AreEqual(text, "Testing Inputs");
// FetchAttributes
// identify the email text box
IWebElement emailTxt = driver.FindElement(By.Name("email_input"));
// fetch the value property associated with the textbox
string valueInfo = emailTxt.GetAttribute("value");
Assert.AreEqual(valueInfo, "admin@localhost");
//Quit the driver
driver.Quit();
}
}
} enabled_value = driver.find_element(name: 'email_input').enabled?/examples/ruby/spec/elements/information_spec.rb
# frozen_string_literal: true
require 'spec_helper'
RSpec.describe 'Element Information' do
let(:driver) { start_session }
let(:url) { 'https://www.selenium.dev/selenium/web/inputs.html' }
before { driver.get(url) }
it 'checks if an element is displayed' do
displayed_value = driver.find_element(name: 'email_input').displayed?
expect(displayed_value).to be_truthy
end
it 'checks if an element is enabled' do
enabled_value = driver.find_element(name: 'email_input').enabled?
expect(enabled_value).to be_truthy
end
it 'checks if an element is selected' do
selected_value = driver.find_element(name: 'email_input').selected?
expect(selected_value).to be_falsey
end
it 'gets the tag name of an element' do
tag_name = driver.find_element(name: 'email_input').tag_name
expect(tag_name).not_to be_empty
end
it 'gets the size and position of an element' do
size = driver.find_element(name: 'email_input').size
expect(size.width).to be_positive
expect(size.height).to be_positive
end
it 'gets the css value of an element' do
css_value = driver.find_element(name: 'email_input').css_value('background-color')
expect(css_value).not_to be_empty
end
it 'gets the text of an element' do
text = driver.find_element(xpath: '//h1').text
expect(text).to eq('Testing Inputs')
end
it 'gets the attribute value of an element' do
attribute_value = driver.find_element(name: 'number_input').attribute('value')
expect(attribute_value).not_to be_empty
end
end
// Resolves Promise and returns boolean value
let element = await driver.findElement(By.name("button_input")).isEnabled();/examples/javascript/test/elements/information.spec.js
const {By, Builder} = require('selenium-webdriver');
const assert = require("assert");
describe('Element Information Test', function () {
let driver;
before(async function () {
driver = await new Builder().forBrowser('chrome').build();
});
beforeEach(async ()=> {
await driver.get('https://www.selenium.dev/selenium/web/inputs.html');
})
it('Check if element is displayed', async function () {
// Resolves Promise and returns boolean value
let result = await driver.findElement(By.name("email_input")).isDisplayed();
assert.equal(result,true);
});
it('Check if button is enabled', async function () {
// Resolves Promise and returns boolean value
let element = await driver.findElement(By.name("button_input")).isEnabled();
assert.equal(element, true);
});
it('Check if checkbox is selected', async function () {
// Returns true if element is checked else returns false
let isSelected = await driver.findElement(By.name("checkbox_input")).isSelected();
assert.equal(isSelected, true);
});
it('Should return the tagname', async function () {
// Returns TagName of the element
let value = await driver.findElement(By.name('email_input')).getTagName();
assert.equal(value, "input");
});
it('Should be able to fetch element size and position ', async function () {
// Returns height, width, x and y position of the element
let object = await driver.findElement(By.name('range_input')).getRect();
assert.ok(object.height!==null)
assert.ok(object.width!==null)
assert.ok(object.y!==null)
assert.ok(object.x!==null)
});
it('Should be able to fetch attributes and properties ', async function () {
// identify the email text box
const emailElement = await driver.findElement(By.xpath('//input[@name="email_input"]'));
//fetch the attribute "name" associated with the textbox
const nameAttribute = await emailElement.getAttribute("name");
assert.equal(nameAttribute, "email_input")
});
after(async () => await driver.quit());
});
describe('Element Information Test', function () {
let driver;
before(async function () {
driver = await new Builder().forBrowser('chrome').build();
});
it('Should return the css specified CSS value', async function () {
await driver.get('https://www.selenium.dev/selenium/web/colorPage.html');
// Returns background color of the element
let value = await driver.findElement(By.id('namedColor')).getCssValue('background-color');
assert.equal(value, "rgba(0, 128, 0, 1)");
});
it('Should return the css specified CSS value', async function () {
await driver.get('https://www.selenium.dev/selenium/web/linked_image.html');
// Returns text of the element
let text = await driver.findElement(By.id('justanotherLink')).getText();
assert.equal(text, "Just another link.");
});
after(async () => await driver.quit());
});
//navigates to url
driver.get("https://www.selenium.dev/selenium/web/inputs.html")
//returns true if element is enabled else returns false
val attr = driver.findElement(By.name("button_input")).isEnabled()是否被选定
此方法确认相关的元素是否 已选定,常用于复选框、单选框、输入框和选择元素中。
该方法返回一个布尔值,如果在当前浏览上下文中 选择了 引用的元素,则返回 True,否则返回 False。
boolean isSelectedCheck = driver.findElement(By.name("checkbox_input")).isSelected();
assertTrue(isSelectedCheck);
/examples/java/src/test/java/dev/selenium/elements/InformationTest.java
package dev.selenium.elements;
import org.junit.jupiter.api.Test;
import org.openqa.selenium.By;
import org.openqa.selenium.Rectangle;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import java.time.Duration;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
public class InformationTest {
@Test
public void informationWithElements() {
WebDriver driver = new ChromeDriver();
driver.manage().timeouts().implicitlyWait(Duration.ofMillis(500));
// Navigate to Url
driver.get("https://www.selenium.dev/selenium/web/inputs.html");
// isDisplayed
// Get boolean value for is element display
boolean isEmailVisible = driver.findElement(By.name("email_input")).isDisplayed();
assertTrue(isEmailVisible);
// isEnabled
// returns true if element is enabled
boolean isEnabledButton = driver.findElement(By.name("button_input")).isEnabled();
assertTrue(isEnabledButton);
// isSelected
// returns true if element is checked
boolean isSelectedCheck = driver.findElement(By.name("checkbox_input")).isSelected();
assertTrue(isSelectedCheck);
// TagName
// returns TagName of the element
String tagNameInp = driver.findElement(By.name("email_input")).getTagName();
assertEquals("input", tagNameInp);
// GetRect
// Returns height, width, x and y coordinates referenced element
Rectangle res = driver.findElement(By.name("range_input")).getRect();
// Rectangle class provides getX,getY, getWidth, getHeight methods
assertEquals(10, res.getX());
// Retrieves the computed style property 'font-size' of field
String cssValue = driver.findElement(By.name("color_input")).getCssValue("font-size");
assertEquals(cssValue, "13.3333px");
// GetText
// Retrieves the text of the element
String text = driver.findElement(By.tagName("h1")).getText();
assertEquals(text, "Testing Inputs");
// FetchAttributes
// identify the email text box
WebElement emailTxt = driver.findElement(By.name(("email_input")));
// fetch the value property associated with the textbox
String valueInfo = emailTxt.getAttribute("value");
assertEquals(valueInfo, "admin@localhost");
driver.quit();
}
}
is_selected_check = driver.find_element(By.NAME, "checkbox_input").is_selected()/examples/python/tests/elements/test_information.py
from selenium import webdriver
from selenium.webdriver.common.by import By
import pytest
def test_informarion():
# Initialize WebDriver
driver = webdriver.Chrome()
driver.implicitly_wait(0.5)
driver.get("https://www.selenium.dev/selenium/web/inputs.html")
# isDisplayed
is_email_visible = driver.find_element(By.NAME, "email_input").is_displayed()
assert is_email_visible == True
# isEnabled
is_enabled_button = driver.find_element(By.NAME, "button_input").is_enabled()
assert is_enabled_button == True
# isSelected
is_selected_check = driver.find_element(By.NAME, "checkbox_input").is_selected()
assert is_selected_check == True
# TagName
tag_name_inp = driver.find_element(By.NAME, "email_input").tag_name
assert tag_name_inp == "input"
# GetRect
rect = driver.find_element(By.NAME, "range_input").rect
assert rect["x"] == 10
# CSS Value
css_value = driver.find_element(By.NAME, "color_input").value_of_css_property(
"font-size"
)
assert css_value == "13.3333px"
# GetText
text = driver.find_element(By.TAG_NAME, "h1").text
assert text == "Testing Inputs"
# FetchAttributes
email_txt = driver.find_element(By.NAME, "email_input")
value_info = email_txt.get_attribute("value")
assert value_info == "admin@localhost"
// isSelected
// returns true if element is checked else returns false
bool isSelectedCheck = driver.FindElement(By.Name("checkbox_input")).Selected;/examples/dotnet/SeleniumDocs/Elements/InformationTest.cs
using System;
using System.Drawing;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using OpenQA.Selenium;
using OpenQA.Selenium.Chrome;
namespace SeleniumDocs.Elements
{
[TestClass]
public class InformationTest
{
[TestMethod]
public void TestInformationCommands(){
WebDriver driver = new ChromeDriver();
driver.Manage().Timeouts().ImplicitWait = TimeSpan.FromMilliseconds(500);
// Navigate to Url
driver.Url= "https://www.selenium.dev/selenium/web/inputs.html";
// isDisplayed
// Get boolean value for is element display
bool isEmailVisible = driver.FindElement(By.Name("email_input")).Displayed;
Assert.AreEqual(isEmailVisible, true);
// isEnabled
// returns true if element is enabled else returns false
bool isEnabledButton = driver.FindElement(By.Name("button_input")).Enabled;
Assert.AreEqual(isEnabledButton, true);
// isSelected
// returns true if element is checked else returns false
bool isSelectedCheck = driver.FindElement(By.Name("checkbox_input")).Selected;
Assert.AreEqual(isSelectedCheck, true);
// TagName
// returns TagName of the element
string tagNameInp = driver.FindElement(By.Name("email_input")).TagName;
Assert.AreEqual(tagNameInp, "input");
// Get Location and Size
// Get Location
IWebElement rangeElement = driver.FindElement(By.Name("range_input"));
Point point = rangeElement.Location;
Assert.IsNotNull(point.X);
// Get Size
int height=rangeElement.Size.Height;
Assert.IsNotNull(height);
// Retrieves the computed style property 'font-size' of field
string cssValue = driver.FindElement(By.Name("color_input")).GetCssValue("font-size");
Assert.AreEqual(cssValue, "13.3333px");
// GetText
// Retrieves the text of the element
string text = driver.FindElement(By.TagName("h1")).Text;
Assert.AreEqual(text, "Testing Inputs");
// FetchAttributes
// identify the email text box
IWebElement emailTxt = driver.FindElement(By.Name("email_input"));
// fetch the value property associated with the textbox
string valueInfo = emailTxt.GetAttribute("value");
Assert.AreEqual(valueInfo, "admin@localhost");
//Quit the driver
driver.Quit();
}
}
} selected_value = driver.find_element(name: 'email_input').selected?/examples/ruby/spec/elements/information_spec.rb
# frozen_string_literal: true
require 'spec_helper'
RSpec.describe 'Element Information' do
let(:driver) { start_session }
let(:url) { 'https://www.selenium.dev/selenium/web/inputs.html' }
before { driver.get(url) }
it 'checks if an element is displayed' do
displayed_value = driver.find_element(name: 'email_input').displayed?
expect(displayed_value).to be_truthy
end
it 'checks if an element is enabled' do
enabled_value = driver.find_element(name: 'email_input').enabled?
expect(enabled_value).to be_truthy
end
it 'checks if an element is selected' do
selected_value = driver.find_element(name: 'email_input').selected?
expect(selected_value).to be_falsey
end
it 'gets the tag name of an element' do
tag_name = driver.find_element(name: 'email_input').tag_name
expect(tag_name).not_to be_empty
end
it 'gets the size and position of an element' do
size = driver.find_element(name: 'email_input').size
expect(size.width).to be_positive
expect(size.height).to be_positive
end
it 'gets the css value of an element' do
css_value = driver.find_element(name: 'email_input').css_value('background-color')
expect(css_value).not_to be_empty
end
it 'gets the text of an element' do
text = driver.find_element(xpath: '//h1').text
expect(text).to eq('Testing Inputs')
end
it 'gets the attribute value of an element' do
attribute_value = driver.find_element(name: 'number_input').attribute('value')
expect(attribute_value).not_to be_empty
end
end
// Returns true if element is checked else returns false
let isSelected = await driver.findElement(By.name("checkbox_input")).isSelected();/examples/javascript/test/elements/information.spec.js
const {By, Builder} = require('selenium-webdriver');
const assert = require("assert");
describe('Element Information Test', function () {
let driver;
before(async function () {
driver = await new Builder().forBrowser('chrome').build();
});
beforeEach(async ()=> {
await driver.get('https://www.selenium.dev/selenium/web/inputs.html');
})
it('Check if element is displayed', async function () {
// Resolves Promise and returns boolean value
let result = await driver.findElement(By.name("email_input")).isDisplayed();
assert.equal(result,true);
});
it('Check if button is enabled', async function () {
// Resolves Promise and returns boolean value
let element = await driver.findElement(By.name("button_input")).isEnabled();
assert.equal(element, true);
});
it('Check if checkbox is selected', async function () {
// Returns true if element is checked else returns false
let isSelected = await driver.findElement(By.name("checkbox_input")).isSelected();
assert.equal(isSelected, true);
});
it('Should return the tagname', async function () {
// Returns TagName of the element
let value = await driver.findElement(By.name('email_input')).getTagName();
assert.equal(value, "input");
});
it('Should be able to fetch element size and position ', async function () {
// Returns height, width, x and y position of the element
let object = await driver.findElement(By.name('range_input')).getRect();
assert.ok(object.height!==null)
assert.ok(object.width!==null)
assert.ok(object.y!==null)
assert.ok(object.x!==null)
});
it('Should be able to fetch attributes and properties ', async function () {
// identify the email text box
const emailElement = await driver.findElement(By.xpath('//input[@name="email_input"]'));
//fetch the attribute "name" associated with the textbox
const nameAttribute = await emailElement.getAttribute("name");
assert.equal(nameAttribute, "email_input")
});
after(async () => await driver.quit());
});
describe('Element Information Test', function () {
let driver;
before(async function () {
driver = await new Builder().forBrowser('chrome').build();
});
it('Should return the css specified CSS value', async function () {
await driver.get('https://www.selenium.dev/selenium/web/colorPage.html');
// Returns background color of the element
let value = await driver.findElement(By.id('namedColor')).getCssValue('background-color');
assert.equal(value, "rgba(0, 128, 0, 1)");
});
it('Should return the css specified CSS value', async function () {
await driver.get('https://www.selenium.dev/selenium/web/linked_image.html');
// Returns text of the element
let text = await driver.findElement(By.id('justanotherLink')).getText();
assert.equal(text, "Just another link.");
});
after(async () => await driver.quit());
});
//navigates to url
driver.get("https://www.selenium.dev/selenium/web/inputs.html")
//returns true if element is checked else returns false
val attr = driver.findElement(By.name("checkbox_input")).isSelected()获取元素标签名
此方法用于获取在当前浏览上下文中具有焦点的被引用元素的TagName。
String tagNameInp = driver.findElement(By.name("email_input")).getTagName();
assertEquals("input", tagNameInp);
/examples/java/src/test/java/dev/selenium/elements/InformationTest.java
package dev.selenium.elements;
import org.junit.jupiter.api.Test;
import org.openqa.selenium.By;
import org.openqa.selenium.Rectangle;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import java.time.Duration;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
public class InformationTest {
@Test
public void informationWithElements() {
WebDriver driver = new ChromeDriver();
driver.manage().timeouts().implicitlyWait(Duration.ofMillis(500));
// Navigate to Url
driver.get("https://www.selenium.dev/selenium/web/inputs.html");
// isDisplayed
// Get boolean value for is element display
boolean isEmailVisible = driver.findElement(By.name("email_input")).isDisplayed();
assertTrue(isEmailVisible);
// isEnabled
// returns true if element is enabled
boolean isEnabledButton = driver.findElement(By.name("button_input")).isEnabled();
assertTrue(isEnabledButton);
// isSelected
// returns true if element is checked
boolean isSelectedCheck = driver.findElement(By.name("checkbox_input")).isSelected();
assertTrue(isSelectedCheck);
// TagName
// returns TagName of the element
String tagNameInp = driver.findElement(By.name("email_input")).getTagName();
assertEquals("input", tagNameInp);
// GetRect
// Returns height, width, x and y coordinates referenced element
Rectangle res = driver.findElement(By.name("range_input")).getRect();
// Rectangle class provides getX,getY, getWidth, getHeight methods
assertEquals(10, res.getX());
// Retrieves the computed style property 'font-size' of field
String cssValue = driver.findElement(By.name("color_input")).getCssValue("font-size");
assertEquals(cssValue, "13.3333px");
// GetText
// Retrieves the text of the element
String text = driver.findElement(By.tagName("h1")).getText();
assertEquals(text, "Testing Inputs");
// FetchAttributes
// identify the email text box
WebElement emailTxt = driver.findElement(By.name(("email_input")));
// fetch the value property associated with the textbox
String valueInfo = emailTxt.getAttribute("value");
assertEquals(valueInfo, "admin@localhost");
driver.quit();
}
}
tag_name_inp = driver.find_element(By.NAME, "email_input").tag_name/examples/python/tests/elements/test_information.py
from selenium import webdriver
from selenium.webdriver.common.by import By
import pytest
def test_informarion():
# Initialize WebDriver
driver = webdriver.Chrome()
driver.implicitly_wait(0.5)
driver.get("https://www.selenium.dev/selenium/web/inputs.html")
# isDisplayed
is_email_visible = driver.find_element(By.NAME, "email_input").is_displayed()
assert is_email_visible == True
# isEnabled
is_enabled_button = driver.find_element(By.NAME, "button_input").is_enabled()
assert is_enabled_button == True
# isSelected
is_selected_check = driver.find_element(By.NAME, "checkbox_input").is_selected()
assert is_selected_check == True
# TagName
tag_name_inp = driver.find_element(By.NAME, "email_input").tag_name
assert tag_name_inp == "input"
# GetRect
rect = driver.find_element(By.NAME, "range_input").rect
assert rect["x"] == 10
# CSS Value
css_value = driver.find_element(By.NAME, "color_input").value_of_css_property(
"font-size"
)
assert css_value == "13.3333px"
# GetText
text = driver.find_element(By.TAG_NAME, "h1").text
assert text == "Testing Inputs"
# FetchAttributes
email_txt = driver.find_element(By.NAME, "email_input")
value_info = email_txt.get_attribute("value")
assert value_info == "admin@localhost"
// TagName
// returns TagName of the element
string tagNameInp = driver.FindElement(By.Name("email_input")).TagName;/examples/dotnet/SeleniumDocs/Elements/InformationTest.cs
using System;
using System.Drawing;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using OpenQA.Selenium;
using OpenQA.Selenium.Chrome;
namespace SeleniumDocs.Elements
{
[TestClass]
public class InformationTest
{
[TestMethod]
public void TestInformationCommands(){
WebDriver driver = new ChromeDriver();
driver.Manage().Timeouts().ImplicitWait = TimeSpan.FromMilliseconds(500);
// Navigate to Url
driver.Url= "https://www.selenium.dev/selenium/web/inputs.html";
// isDisplayed
// Get boolean value for is element display
bool isEmailVisible = driver.FindElement(By.Name("email_input")).Displayed;
Assert.AreEqual(isEmailVisible, true);
// isEnabled
// returns true if element is enabled else returns false
bool isEnabledButton = driver.FindElement(By.Name("button_input")).Enabled;
Assert.AreEqual(isEnabledButton, true);
// isSelected
// returns true if element is checked else returns false
bool isSelectedCheck = driver.FindElement(By.Name("checkbox_input")).Selected;
Assert.AreEqual(isSelectedCheck, true);
// TagName
// returns TagName of the element
string tagNameInp = driver.FindElement(By.Name("email_input")).TagName;
Assert.AreEqual(tagNameInp, "input");
// Get Location and Size
// Get Location
IWebElement rangeElement = driver.FindElement(By.Name("range_input"));
Point point = rangeElement.Location;
Assert.IsNotNull(point.X);
// Get Size
int height=rangeElement.Size.Height;
Assert.IsNotNull(height);
// Retrieves the computed style property 'font-size' of field
string cssValue = driver.FindElement(By.Name("color_input")).GetCssValue("font-size");
Assert.AreEqual(cssValue, "13.3333px");
// GetText
// Retrieves the text of the element
string text = driver.FindElement(By.TagName("h1")).Text;
Assert.AreEqual(text, "Testing Inputs");
// FetchAttributes
// identify the email text box
IWebElement emailTxt = driver.FindElement(By.Name("email_input"));
// fetch the value property associated with the textbox
string valueInfo = emailTxt.GetAttribute("value");
Assert.AreEqual(valueInfo, "admin@localhost");
//Quit the driver
driver.Quit();
}
}
} tag_name = driver.find_element(name: 'email_input').tag_name/examples/ruby/spec/elements/information_spec.rb
# frozen_string_literal: true
require 'spec_helper'
RSpec.describe 'Element Information' do
let(:driver) { start_session }
let(:url) { 'https://www.selenium.dev/selenium/web/inputs.html' }
before { driver.get(url) }
it 'checks if an element is displayed' do
displayed_value = driver.find_element(name: 'email_input').displayed?
expect(displayed_value).to be_truthy
end
it 'checks if an element is enabled' do
enabled_value = driver.find_element(name: 'email_input').enabled?
expect(enabled_value).to be_truthy
end
it 'checks if an element is selected' do
selected_value = driver.find_element(name: 'email_input').selected?
expect(selected_value).to be_falsey
end
it 'gets the tag name of an element' do
tag_name = driver.find_element(name: 'email_input').tag_name
expect(tag_name).not_to be_empty
end
it 'gets the size and position of an element' do
size = driver.find_element(name: 'email_input').size
expect(size.width).to be_positive
expect(size.height).to be_positive
end
it 'gets the css value of an element' do
css_value = driver.find_element(name: 'email_input').css_value('background-color')
expect(css_value).not_to be_empty
end
it 'gets the text of an element' do
text = driver.find_element(xpath: '//h1').text
expect(text).to eq('Testing Inputs')
end
it 'gets the attribute value of an element' do
attribute_value = driver.find_element(name: 'number_input').attribute('value')
expect(attribute_value).not_to be_empty
end
end
// Returns TagName of the element
let value = await driver.findElement(By.name('email_input')).getTagName();/examples/javascript/test/elements/information.spec.js
const {By, Builder} = require('selenium-webdriver');
const assert = require("assert");
describe('Element Information Test', function () {
let driver;
before(async function () {
driver = await new Builder().forBrowser('chrome').build();
});
beforeEach(async ()=> {
await driver.get('https://www.selenium.dev/selenium/web/inputs.html');
})
it('Check if element is displayed', async function () {
// Resolves Promise and returns boolean value
let result = await driver.findElement(By.name("email_input")).isDisplayed();
assert.equal(result,true);
});
it('Check if button is enabled', async function () {
// Resolves Promise and returns boolean value
let element = await driver.findElement(By.name("button_input")).isEnabled();
assert.equal(element, true);
});
it('Check if checkbox is selected', async function () {
// Returns true if element is checked else returns false
let isSelected = await driver.findElement(By.name("checkbox_input")).isSelected();
assert.equal(isSelected, true);
});
it('Should return the tagname', async function () {
// Returns TagName of the element
let value = await driver.findElement(By.name('email_input')).getTagName();
assert.equal(value, "input");
});
it('Should be able to fetch element size and position ', async function () {
// Returns height, width, x and y position of the element
let object = await driver.findElement(By.name('range_input')).getRect();
assert.ok(object.height!==null)
assert.ok(object.width!==null)
assert.ok(object.y!==null)
assert.ok(object.x!==null)
});
it('Should be able to fetch attributes and properties ', async function () {
// identify the email text box
const emailElement = await driver.findElement(By.xpath('//input[@name="email_input"]'));
//fetch the attribute "name" associated with the textbox
const nameAttribute = await emailElement.getAttribute("name");
assert.equal(nameAttribute, "email_input")
});
after(async () => await driver.quit());
});
describe('Element Information Test', function () {
let driver;
before(async function () {
driver = await new Builder().forBrowser('chrome').build();
});
it('Should return the css specified CSS value', async function () {
await driver.get('https://www.selenium.dev/selenium/web/colorPage.html');
// Returns background color of the element
let value = await driver.findElement(By.id('namedColor')).getCssValue('background-color');
assert.equal(value, "rgba(0, 128, 0, 1)");
});
it('Should return the css specified CSS value', async function () {
await driver.get('https://www.selenium.dev/selenium/web/linked_image.html');
// Returns text of the element
let text = await driver.findElement(By.id('justanotherLink')).getText();
assert.equal(text, "Just another link.");
});
after(async () => await driver.quit());
});
//navigates to url
driver.get("https://www.selenium.dev/selenium/web/inputs.html")
//returns TagName of the element
val attr = driver.findElement(By.name("email_input")).getTagName()位置和大小
用于获取参照元素的尺寸和坐标。
提取的数据主体包含以下详细信息:
- 元素左上角的X轴位置
- 元素左上角的y轴位置
- 元素的高度
- 元素的宽度
Rectangle res = driver.findElement(By.name("range_input")).getRect();
// Rectangle class provides getX,getY, getWidth, getHeight methods
assertEquals(10, res.getX());
/examples/java/src/test/java/dev/selenium/elements/InformationTest.java
package dev.selenium.elements;
import org.junit.jupiter.api.Test;
import org.openqa.selenium.By;
import org.openqa.selenium.Rectangle;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import java.time.Duration;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
public class InformationTest {
@Test
public void informationWithElements() {
WebDriver driver = new ChromeDriver();
driver.manage().timeouts().implicitlyWait(Duration.ofMillis(500));
// Navigate to Url
driver.get("https://www.selenium.dev/selenium/web/inputs.html");
// isDisplayed
// Get boolean value for is element display
boolean isEmailVisible = driver.findElement(By.name("email_input")).isDisplayed();
assertTrue(isEmailVisible);
// isEnabled
// returns true if element is enabled
boolean isEnabledButton = driver.findElement(By.name("button_input")).isEnabled();
assertTrue(isEnabledButton);
// isSelected
// returns true if element is checked
boolean isSelectedCheck = driver.findElement(By.name("checkbox_input")).isSelected();
assertTrue(isSelectedCheck);
// TagName
// returns TagName of the element
String tagNameInp = driver.findElement(By.name("email_input")).getTagName();
assertEquals("input", tagNameInp);
// GetRect
// Returns height, width, x and y coordinates referenced element
Rectangle res = driver.findElement(By.name("range_input")).getRect();
// Rectangle class provides getX,getY, getWidth, getHeight methods
assertEquals(10, res.getX());
// Retrieves the computed style property 'font-size' of field
String cssValue = driver.findElement(By.name("color_input")).getCssValue("font-size");
assertEquals(cssValue, "13.3333px");
// GetText
// Retrieves the text of the element
String text = driver.findElement(By.tagName("h1")).getText();
assertEquals(text, "Testing Inputs");
// FetchAttributes
// identify the email text box
WebElement emailTxt = driver.findElement(By.name(("email_input")));
// fetch the value property associated with the textbox
String valueInfo = emailTxt.getAttribute("value");
assertEquals(valueInfo, "admin@localhost");
driver.quit();
}
}
rect = driver.find_element(By.NAME, "range_input").rect/examples/python/tests/elements/test_information.py
from selenium import webdriver
from selenium.webdriver.common.by import By
import pytest
def test_informarion():
# Initialize WebDriver
driver = webdriver.Chrome()
driver.implicitly_wait(0.5)
driver.get("https://www.selenium.dev/selenium/web/inputs.html")
# isDisplayed
is_email_visible = driver.find_element(By.NAME, "email_input").is_displayed()
assert is_email_visible == True
# isEnabled
is_enabled_button = driver.find_element(By.NAME, "button_input").is_enabled()
assert is_enabled_button == True
# isSelected
is_selected_check = driver.find_element(By.NAME, "checkbox_input").is_selected()
assert is_selected_check == True
# TagName
tag_name_inp = driver.find_element(By.NAME, "email_input").tag_name
assert tag_name_inp == "input"
# GetRect
rect = driver.find_element(By.NAME, "range_input").rect
assert rect["x"] == 10
# CSS Value
css_value = driver.find_element(By.NAME, "color_input").value_of_css_property(
"font-size"
)
assert css_value == "13.3333px"
# GetText
text = driver.find_element(By.TAG_NAME, "h1").text
assert text == "Testing Inputs"
# FetchAttributes
email_txt = driver.find_element(By.NAME, "email_input")
value_info = email_txt.get_attribute("value")
assert value_info == "admin@localhost"
// Get Location and Size
// Get Location
IWebElement rangeElement = driver.FindElement(By.Name("range_input"));
Point point = rangeElement.Location;/examples/dotnet/SeleniumDocs/Elements/InformationTest.cs
using System;
using System.Drawing;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using OpenQA.Selenium;
using OpenQA.Selenium.Chrome;
namespace SeleniumDocs.Elements
{
[TestClass]
public class InformationTest
{
[TestMethod]
public void TestInformationCommands(){
WebDriver driver = new ChromeDriver();
driver.Manage().Timeouts().ImplicitWait = TimeSpan.FromMilliseconds(500);
// Navigate to Url
driver.Url= "https://www.selenium.dev/selenium/web/inputs.html";
// isDisplayed
// Get boolean value for is element display
bool isEmailVisible = driver.FindElement(By.Name("email_input")).Displayed;
Assert.AreEqual(isEmailVisible, true);
// isEnabled
// returns true if element is enabled else returns false
bool isEnabledButton = driver.FindElement(By.Name("button_input")).Enabled;
Assert.AreEqual(isEnabledButton, true);
// isSelected
// returns true if element is checked else returns false
bool isSelectedCheck = driver.FindElement(By.Name("checkbox_input")).Selected;
Assert.AreEqual(isSelectedCheck, true);
// TagName
// returns TagName of the element
string tagNameInp = driver.FindElement(By.Name("email_input")).TagName;
Assert.AreEqual(tagNameInp, "input");
// Get Location and Size
// Get Location
IWebElement rangeElement = driver.FindElement(By.Name("range_input"));
Point point = rangeElement.Location;
Assert.IsNotNull(point.X);
// Get Size
int height=rangeElement.Size.Height;
Assert.IsNotNull(height);
// Retrieves the computed style property 'font-size' of field
string cssValue = driver.FindElement(By.Name("color_input")).GetCssValue("font-size");
Assert.AreEqual(cssValue, "13.3333px");
// GetText
// Retrieves the text of the element
string text = driver.FindElement(By.TagName("h1")).Text;
Assert.AreEqual(text, "Testing Inputs");
// FetchAttributes
// identify the email text box
IWebElement emailTxt = driver.FindElement(By.Name("email_input"));
// fetch the value property associated with the textbox
string valueInfo = emailTxt.GetAttribute("value");
Assert.AreEqual(valueInfo, "admin@localhost");
//Quit the driver
driver.Quit();
}
}
} size = driver.find_element(name: 'email_input').size/examples/ruby/spec/elements/information_spec.rb
# frozen_string_literal: true
require 'spec_helper'
RSpec.describe 'Element Information' do
let(:driver) { start_session }
let(:url) { 'https://www.selenium.dev/selenium/web/inputs.html' }
before { driver.get(url) }
it 'checks if an element is displayed' do
displayed_value = driver.find_element(name: 'email_input').displayed?
expect(displayed_value).to be_truthy
end
it 'checks if an element is enabled' do
enabled_value = driver.find_element(name: 'email_input').enabled?
expect(enabled_value).to be_truthy
end
it 'checks if an element is selected' do
selected_value = driver.find_element(name: 'email_input').selected?
expect(selected_value).to be_falsey
end
it 'gets the tag name of an element' do
tag_name = driver.find_element(name: 'email_input').tag_name
expect(tag_name).not_to be_empty
end
it 'gets the size and position of an element' do
size = driver.find_element(name: 'email_input').size
expect(size.width).to be_positive
expect(size.height).to be_positive
end
it 'gets the css value of an element' do
css_value = driver.find_element(name: 'email_input').css_value('background-color')
expect(css_value).not_to be_empty
end
it 'gets the text of an element' do
text = driver.find_element(xpath: '//h1').text
expect(text).to eq('Testing Inputs')
end
it 'gets the attribute value of an element' do
attribute_value = driver.find_element(name: 'number_input').attribute('value')
expect(attribute_value).not_to be_empty
end
end
let object = await driver.findElement(By.name('range_input')).getRect();/examples/javascript/test/elements/information.spec.js
const {By, Builder} = require('selenium-webdriver');
const assert = require("assert");
describe('Element Information Test', function () {
let driver;
before(async function () {
driver = await new Builder().forBrowser('chrome').build();
});
beforeEach(async ()=> {
await driver.get('https://www.selenium.dev/selenium/web/inputs.html');
})
it('Check if element is displayed', async function () {
// Resolves Promise and returns boolean value
let result = await driver.findElement(By.name("email_input")).isDisplayed();
assert.equal(result,true);
});
it('Check if button is enabled', async function () {
// Resolves Promise and returns boolean value
let element = await driver.findElement(By.name("button_input")).isEnabled();
assert.equal(element, true);
});
it('Check if checkbox is selected', async function () {
// Returns true if element is checked else returns false
let isSelected = await driver.findElement(By.name("checkbox_input")).isSelected();
assert.equal(isSelected, true);
});
it('Should return the tagname', async function () {
// Returns TagName of the element
let value = await driver.findElement(By.name('email_input')).getTagName();
assert.equal(value, "input");
});
it('Should be able to fetch element size and position ', async function () {
// Returns height, width, x and y position of the element
let object = await driver.findElement(By.name('range_input')).getRect();
assert.ok(object.height!==null)
assert.ok(object.width!==null)
assert.ok(object.y!==null)
assert.ok(object.x!==null)
});
it('Should be able to fetch attributes and properties ', async function () {
// identify the email text box
const emailElement = await driver.findElement(By.xpath('//input[@name="email_input"]'));
//fetch the attribute "name" associated with the textbox
const nameAttribute = await emailElement.getAttribute("name");
assert.equal(nameAttribute, "email_input")
});
after(async () => await driver.quit());
});
describe('Element Information Test', function () {
let driver;
before(async function () {
driver = await new Builder().forBrowser('chrome').build();
});
it('Should return the css specified CSS value', async function () {
await driver.get('https://www.selenium.dev/selenium/web/colorPage.html');
// Returns background color of the element
let value = await driver.findElement(By.id('namedColor')).getCssValue('background-color');
assert.equal(value, "rgba(0, 128, 0, 1)");
});
it('Should return the css specified CSS value', async function () {
await driver.get('https://www.selenium.dev/selenium/web/linked_image.html');
// Returns text of the element
let text = await driver.findElement(By.id('justanotherLink')).getText();
assert.equal(text, "Just another link.");
});
after(async () => await driver.quit());
});
// Navigate to url
driver.get("https://www.selenium.dev/selenium/web/inputs.html")
// Returns height, width, x and y coordinates referenced element
val res = driver.findElement(By.name("range_input")).rect
// Rectangle class provides getX,getY, getWidth, getHeight methods
println(res.getX())获取元素CSS值
获取当前浏览上下文中元素的特定计算样式属性的值。
String cssValue = driver.findElement(By.name("color_input")).getCssValue("font-size");
assertEquals(cssValue, "13.3333px");
/examples/java/src/test/java/dev/selenium/elements/InformationTest.java
package dev.selenium.elements;
import org.junit.jupiter.api.Test;
import org.openqa.selenium.By;
import org.openqa.selenium.Rectangle;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import java.time.Duration;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
public class InformationTest {
@Test
public void informationWithElements() {
WebDriver driver = new ChromeDriver();
driver.manage().timeouts().implicitlyWait(Duration.ofMillis(500));
// Navigate to Url
driver.get("https://www.selenium.dev/selenium/web/inputs.html");
// isDisplayed
// Get boolean value for is element display
boolean isEmailVisible = driver.findElement(By.name("email_input")).isDisplayed();
assertTrue(isEmailVisible);
// isEnabled
// returns true if element is enabled
boolean isEnabledButton = driver.findElement(By.name("button_input")).isEnabled();
assertTrue(isEnabledButton);
// isSelected
// returns true if element is checked
boolean isSelectedCheck = driver.findElement(By.name("checkbox_input")).isSelected();
assertTrue(isSelectedCheck);
// TagName
// returns TagName of the element
String tagNameInp = driver.findElement(By.name("email_input")).getTagName();
assertEquals("input", tagNameInp);
// GetRect
// Returns height, width, x and y coordinates referenced element
Rectangle res = driver.findElement(By.name("range_input")).getRect();
// Rectangle class provides getX,getY, getWidth, getHeight methods
assertEquals(10, res.getX());
// Retrieves the computed style property 'font-size' of field
String cssValue = driver.findElement(By.name("color_input")).getCssValue("font-size");
assertEquals(cssValue, "13.3333px");
// GetText
// Retrieves the text of the element
String text = driver.findElement(By.tagName("h1")).getText();
assertEquals(text, "Testing Inputs");
// FetchAttributes
// identify the email text box
WebElement emailTxt = driver.findElement(By.name(("email_input")));
// fetch the value property associated with the textbox
String valueInfo = emailTxt.getAttribute("value");
assertEquals(valueInfo, "admin@localhost");
driver.quit();
}
}
css_value = driver.find_element(By.NAME, "color_input").value_of_css_property(
"font-size"
)/examples/python/tests/elements/test_information.py
from selenium import webdriver
from selenium.webdriver.common.by import By
import pytest
def test_informarion():
# Initialize WebDriver
driver = webdriver.Chrome()
driver.implicitly_wait(0.5)
driver.get("https://www.selenium.dev/selenium/web/inputs.html")
# isDisplayed
is_email_visible = driver.find_element(By.NAME, "email_input").is_displayed()
assert is_email_visible == True
# isEnabled
is_enabled_button = driver.find_element(By.NAME, "button_input").is_enabled()
assert is_enabled_button == True
# isSelected
is_selected_check = driver.find_element(By.NAME, "checkbox_input").is_selected()
assert is_selected_check == True
# TagName
tag_name_inp = driver.find_element(By.NAME, "email_input").tag_name
assert tag_name_inp == "input"
# GetRect
rect = driver.find_element(By.NAME, "range_input").rect
assert rect["x"] == 10
# CSS Value
css_value = driver.find_element(By.NAME, "color_input").value_of_css_property(
"font-size"
)
assert css_value == "13.3333px"
# GetText
text = driver.find_element(By.TAG_NAME, "h1").text
assert text == "Testing Inputs"
# FetchAttributes
email_txt = driver.find_element(By.NAME, "email_input")
value_info = email_txt.get_attribute("value")
assert value_info == "admin@localhost"
// Retrieves the computed style property 'font-size' of field
string cssValue = driver.FindElement(By.Name("color_input")).GetCssValue("font-size");/examples/dotnet/SeleniumDocs/Elements/InformationTest.cs
using System;
using System.Drawing;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using OpenQA.Selenium;
using OpenQA.Selenium.Chrome;
namespace SeleniumDocs.Elements
{
[TestClass]
public class InformationTest
{
[TestMethod]
public void TestInformationCommands(){
WebDriver driver = new ChromeDriver();
driver.Manage().Timeouts().ImplicitWait = TimeSpan.FromMilliseconds(500);
// Navigate to Url
driver.Url= "https://www.selenium.dev/selenium/web/inputs.html";
// isDisplayed
// Get boolean value for is element display
bool isEmailVisible = driver.FindElement(By.Name("email_input")).Displayed;
Assert.AreEqual(isEmailVisible, true);
// isEnabled
// returns true if element is enabled else returns false
bool isEnabledButton = driver.FindElement(By.Name("button_input")).Enabled;
Assert.AreEqual(isEnabledButton, true);
// isSelected
// returns true if element is checked else returns false
bool isSelectedCheck = driver.FindElement(By.Name("checkbox_input")).Selected;
Assert.AreEqual(isSelectedCheck, true);
// TagName
// returns TagName of the element
string tagNameInp = driver.FindElement(By.Name("email_input")).TagName;
Assert.AreEqual(tagNameInp, "input");
// Get Location and Size
// Get Location
IWebElement rangeElement = driver.FindElement(By.Name("range_input"));
Point point = rangeElement.Location;
Assert.IsNotNull(point.X);
// Get Size
int height=rangeElement.Size.Height;
Assert.IsNotNull(height);
// Retrieves the computed style property 'font-size' of field
string cssValue = driver.FindElement(By.Name("color_input")).GetCssValue("font-size");
Assert.AreEqual(cssValue, "13.3333px");
// GetText
// Retrieves the text of the element
string text = driver.FindElement(By.TagName("h1")).Text;
Assert.AreEqual(text, "Testing Inputs");
// FetchAttributes
// identify the email text box
IWebElement emailTxt = driver.FindElement(By.Name("email_input"));
// fetch the value property associated with the textbox
string valueInfo = emailTxt.GetAttribute("value");
Assert.AreEqual(valueInfo, "admin@localhost");
//Quit the driver
driver.Quit();
}
}
} css_value = driver.find_element(name: 'email_input').css_value('background-color')/examples/ruby/spec/elements/information_spec.rb
# frozen_string_literal: true
require 'spec_helper'
RSpec.describe 'Element Information' do
let(:driver) { start_session }
let(:url) { 'https://www.selenium.dev/selenium/web/inputs.html' }
before { driver.get(url) }
it 'checks if an element is displayed' do
displayed_value = driver.find_element(name: 'email_input').displayed?
expect(displayed_value).to be_truthy
end
it 'checks if an element is enabled' do
enabled_value = driver.find_element(name: 'email_input').enabled?
expect(enabled_value).to be_truthy
end
it 'checks if an element is selected' do
selected_value = driver.find_element(name: 'email_input').selected?
expect(selected_value).to be_falsey
end
it 'gets the tag name of an element' do
tag_name = driver.find_element(name: 'email_input').tag_name
expect(tag_name).not_to be_empty
end
it 'gets the size and position of an element' do
size = driver.find_element(name: 'email_input').size
expect(size.width).to be_positive
expect(size.height).to be_positive
end
it 'gets the css value of an element' do
css_value = driver.find_element(name: 'email_input').css_value('background-color')
expect(css_value).not_to be_empty
end
it 'gets the text of an element' do
text = driver.find_element(xpath: '//h1').text
expect(text).to eq('Testing Inputs')
end
it 'gets the attribute value of an element' do
attribute_value = driver.find_element(name: 'number_input').attribute('value')
expect(attribute_value).not_to be_empty
end
end
await driver.get('https://www.selenium.dev/selenium/web/colorPage.html');
// Returns background color of the element
let value = await driver.findElement(By.id('namedColor')).getCssValue('background-color');/examples/javascript/test/elements/information.spec.js
const {By, Builder} = require('selenium-webdriver');
const assert = require("assert");
describe('Element Information Test', function () {
let driver;
before(async function () {
driver = await new Builder().forBrowser('chrome').build();
});
beforeEach(async ()=> {
await driver.get('https://www.selenium.dev/selenium/web/inputs.html');
})
it('Check if element is displayed', async function () {
// Resolves Promise and returns boolean value
let result = await driver.findElement(By.name("email_input")).isDisplayed();
assert.equal(result,true);
});
it('Check if button is enabled', async function () {
// Resolves Promise and returns boolean value
let element = await driver.findElement(By.name("button_input")).isEnabled();
assert.equal(element, true);
});
it('Check if checkbox is selected', async function () {
// Returns true if element is checked else returns false
let isSelected = await driver.findElement(By.name("checkbox_input")).isSelected();
assert.equal(isSelected, true);
});
it('Should return the tagname', async function () {
// Returns TagName of the element
let value = await driver.findElement(By.name('email_input')).getTagName();
assert.equal(value, "input");
});
it('Should be able to fetch element size and position ', async function () {
// Returns height, width, x and y position of the element
let object = await driver.findElement(By.name('range_input')).getRect();
assert.ok(object.height!==null)
assert.ok(object.width!==null)
assert.ok(object.y!==null)
assert.ok(object.x!==null)
});
it('Should be able to fetch attributes and properties ', async function () {
// identify the email text box
const emailElement = await driver.findElement(By.xpath('//input[@name="email_input"]'));
//fetch the attribute "name" associated with the textbox
const nameAttribute = await emailElement.getAttribute("name");
assert.equal(nameAttribute, "email_input")
});
after(async () => await driver.quit());
});
describe('Element Information Test', function () {
let driver;
before(async function () {
driver = await new Builder().forBrowser('chrome').build();
});
it('Should return the css specified CSS value', async function () {
await driver.get('https://www.selenium.dev/selenium/web/colorPage.html');
// Returns background color of the element
let value = await driver.findElement(By.id('namedColor')).getCssValue('background-color');
assert.equal(value, "rgba(0, 128, 0, 1)");
});
it('Should return the css specified CSS value', async function () {
await driver.get('https://www.selenium.dev/selenium/web/linked_image.html');
// Returns text of the element
let text = await driver.findElement(By.id('justanotherLink')).getText();
assert.equal(text, "Just another link.");
});
after(async () => await driver.quit());
});
// Navigate to Url
driver.get("https://www.selenium.dev/selenium/web/colorPage.html")
// Retrieves the computed style property 'color' of linktext
val cssValue = driver.findElement(By.id("namedColor")).getCssValue("background-color")文本内容
获取特定元素渲染后的文本内容。
String text = driver.findElement(By.tagName("h1")).getText();
assertEquals(text, "Testing Inputs");
/examples/java/src/test/java/dev/selenium/elements/InformationTest.java
package dev.selenium.elements;
import org.junit.jupiter.api.Test;
import org.openqa.selenium.By;
import org.openqa.selenium.Rectangle;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import java.time.Duration;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
public class InformationTest {
@Test
public void informationWithElements() {
WebDriver driver = new ChromeDriver();
driver.manage().timeouts().implicitlyWait(Duration.ofMillis(500));
// Navigate to Url
driver.get("https://www.selenium.dev/selenium/web/inputs.html");
// isDisplayed
// Get boolean value for is element display
boolean isEmailVisible = driver.findElement(By.name("email_input")).isDisplayed();
assertTrue(isEmailVisible);
// isEnabled
// returns true if element is enabled
boolean isEnabledButton = driver.findElement(By.name("button_input")).isEnabled();
assertTrue(isEnabledButton);
// isSelected
// returns true if element is checked
boolean isSelectedCheck = driver.findElement(By.name("checkbox_input")).isSelected();
assertTrue(isSelectedCheck);
// TagName
// returns TagName of the element
String tagNameInp = driver.findElement(By.name("email_input")).getTagName();
assertEquals("input", tagNameInp);
// GetRect
// Returns height, width, x and y coordinates referenced element
Rectangle res = driver.findElement(By.name("range_input")).getRect();
// Rectangle class provides getX,getY, getWidth, getHeight methods
assertEquals(10, res.getX());
// Retrieves the computed style property 'font-size' of field
String cssValue = driver.findElement(By.name("color_input")).getCssValue("font-size");
assertEquals(cssValue, "13.3333px");
// GetText
// Retrieves the text of the element
String text = driver.findElement(By.tagName("h1")).getText();
assertEquals(text, "Testing Inputs");
// FetchAttributes
// identify the email text box
WebElement emailTxt = driver.findElement(By.name(("email_input")));
// fetch the value property associated with the textbox
String valueInfo = emailTxt.getAttribute("value");
assertEquals(valueInfo, "admin@localhost");
driver.quit();
}
}
text = driver.find_element(By.TAG_NAME, "h1").text/examples/python/tests/elements/test_information.py
from selenium import webdriver
from selenium.webdriver.common.by import By
import pytest
def test_informarion():
# Initialize WebDriver
driver = webdriver.Chrome()
driver.implicitly_wait(0.5)
driver.get("https://www.selenium.dev/selenium/web/inputs.html")
# isDisplayed
is_email_visible = driver.find_element(By.NAME, "email_input").is_displayed()
assert is_email_visible == True
# isEnabled
is_enabled_button = driver.find_element(By.NAME, "button_input").is_enabled()
assert is_enabled_button == True
# isSelected
is_selected_check = driver.find_element(By.NAME, "checkbox_input").is_selected()
assert is_selected_check == True
# TagName
tag_name_inp = driver.find_element(By.NAME, "email_input").tag_name
assert tag_name_inp == "input"
# GetRect
rect = driver.find_element(By.NAME, "range_input").rect
assert rect["x"] == 10
# CSS Value
css_value = driver.find_element(By.NAME, "color_input").value_of_css_property(
"font-size"
)
assert css_value == "13.3333px"
# GetText
text = driver.find_element(By.TAG_NAME, "h1").text
assert text == "Testing Inputs"
# FetchAttributes
email_txt = driver.find_element(By.NAME, "email_input")
value_info = email_txt.get_attribute("value")
assert value_info == "admin@localhost"
// GetText
// Retrieves the text of the element
string text = driver.FindElement(By.TagName("h1")).Text;/examples/dotnet/SeleniumDocs/Elements/InformationTest.cs
using System;
using System.Drawing;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using OpenQA.Selenium;
using OpenQA.Selenium.Chrome;
namespace SeleniumDocs.Elements
{
[TestClass]
public class InformationTest
{
[TestMethod]
public void TestInformationCommands(){
WebDriver driver = new ChromeDriver();
driver.Manage().Timeouts().ImplicitWait = TimeSpan.FromMilliseconds(500);
// Navigate to Url
driver.Url= "https://www.selenium.dev/selenium/web/inputs.html";
// isDisplayed
// Get boolean value for is element display
bool isEmailVisible = driver.FindElement(By.Name("email_input")).Displayed;
Assert.AreEqual(isEmailVisible, true);
// isEnabled
// returns true if element is enabled else returns false
bool isEnabledButton = driver.FindElement(By.Name("button_input")).Enabled;
Assert.AreEqual(isEnabledButton, true);
// isSelected
// returns true if element is checked else returns false
bool isSelectedCheck = driver.FindElement(By.Name("checkbox_input")).Selected;
Assert.AreEqual(isSelectedCheck, true);
// TagName
// returns TagName of the element
string tagNameInp = driver.FindElement(By.Name("email_input")).TagName;
Assert.AreEqual(tagNameInp, "input");
// Get Location and Size
// Get Location
IWebElement rangeElement = driver.FindElement(By.Name("range_input"));
Point point = rangeElement.Location;
Assert.IsNotNull(point.X);
// Get Size
int height=rangeElement.Size.Height;
Assert.IsNotNull(height);
// Retrieves the computed style property 'font-size' of field
string cssValue = driver.FindElement(By.Name("color_input")).GetCssValue("font-size");
Assert.AreEqual(cssValue, "13.3333px");
// GetText
// Retrieves the text of the element
string text = driver.FindElement(By.TagName("h1")).Text;
Assert.AreEqual(text, "Testing Inputs");
// FetchAttributes
// identify the email text box
IWebElement emailTxt = driver.FindElement(By.Name("email_input"));
// fetch the value property associated with the textbox
string valueInfo = emailTxt.GetAttribute("value");
Assert.AreEqual(valueInfo, "admin@localhost");
//Quit the driver
driver.Quit();
}
}
} text = driver.find_element(xpath: '//h1').text/examples/ruby/spec/elements/information_spec.rb
# frozen_string_literal: true
require 'spec_helper'
RSpec.describe 'Element Information' do
let(:driver) { start_session }
let(:url) { 'https://www.selenium.dev/selenium/web/inputs.html' }
before { driver.get(url) }
it 'checks if an element is displayed' do
displayed_value = driver.find_element(name: 'email_input').displayed?
expect(displayed_value).to be_truthy
end
it 'checks if an element is enabled' do
enabled_value = driver.find_element(name: 'email_input').enabled?
expect(enabled_value).to be_truthy
end
it 'checks if an element is selected' do
selected_value = driver.find_element(name: 'email_input').selected?
expect(selected_value).to be_falsey
end
it 'gets the tag name of an element' do
tag_name = driver.find_element(name: 'email_input').tag_name
expect(tag_name).not_to be_empty
end
it 'gets the size and position of an element' do
size = driver.find_element(name: 'email_input').size
expect(size.width).to be_positive
expect(size.height).to be_positive
end
it 'gets the css value of an element' do
css_value = driver.find_element(name: 'email_input').css_value('background-color')
expect(css_value).not_to be_empty
end
it 'gets the text of an element' do
text = driver.find_element(xpath: '//h1').text
expect(text).to eq('Testing Inputs')
end
it 'gets the attribute value of an element' do
attribute_value = driver.find_element(name: 'number_input').attribute('value')
expect(attribute_value).not_to be_empty
end
end
await driver.get('https://www.selenium.dev/selenium/web/linked_image.html');
// Returns text of the element
let text = await driver.findElement(By.id('justanotherLink')).getText();/examples/javascript/test/elements/information.spec.js
const {By, Builder} = require('selenium-webdriver');
const assert = require("assert");
describe('Element Information Test', function () {
let driver;
before(async function () {
driver = await new Builder().forBrowser('chrome').build();
});
beforeEach(async ()=> {
await driver.get('https://www.selenium.dev/selenium/web/inputs.html');
})
it('Check if element is displayed', async function () {
// Resolves Promise and returns boolean value
let result = await driver.findElement(By.name("email_input")).isDisplayed();
assert.equal(result,true);
});
it('Check if button is enabled', async function () {
// Resolves Promise and returns boolean value
let element = await driver.findElement(By.name("button_input")).isEnabled();
assert.equal(element, true);
});
it('Check if checkbox is selected', async function () {
// Returns true if element is checked else returns false
let isSelected = await driver.findElement(By.name("checkbox_input")).isSelected();
assert.equal(isSelected, true);
});
it('Should return the tagname', async function () {
// Returns TagName of the element
let value = await driver.findElement(By.name('email_input')).getTagName();
assert.equal(value, "input");
});
it('Should be able to fetch element size and position ', async function () {
// Returns height, width, x and y position of the element
let object = await driver.findElement(By.name('range_input')).getRect();
assert.ok(object.height!==null)
assert.ok(object.width!==null)
assert.ok(object.y!==null)
assert.ok(object.x!==null)
});
it('Should be able to fetch attributes and properties ', async function () {
// identify the email text box
const emailElement = await driver.findElement(By.xpath('//input[@name="email_input"]'));
//fetch the attribute "name" associated with the textbox
const nameAttribute = await emailElement.getAttribute("name");
assert.equal(nameAttribute, "email_input")
});
after(async () => await driver.quit());
});
describe('Element Information Test', function () {
let driver;
before(async function () {
driver = await new Builder().forBrowser('chrome').build();
});
it('Should return the css specified CSS value', async function () {
await driver.get('https://www.selenium.dev/selenium/web/colorPage.html');
// Returns background color of the element
let value = await driver.findElement(By.id('namedColor')).getCssValue('background-color');
assert.equal(value, "rgba(0, 128, 0, 1)");
});
it('Should return the css specified CSS value', async function () {
await driver.get('https://www.selenium.dev/selenium/web/linked_image.html');
// Returns text of the element
let text = await driver.findElement(By.id('justanotherLink')).getText();
assert.equal(text, "Just another link.");
});
after(async () => await driver.quit());
});
// Navigate to URL
driver.get("https://www.selenium.dev/selenium/web/linked_image.html")
// retrieves the text of the element
val text = driver.findElement(By.id("justanotherlink")).getText()获取特性或属性
获取与 DOM 属性关联的运行时的值。 它返回与该元素的 DOM 特性或属性关联的数据。
WebElement emailTxt = driver.findElement(By.name(("email_input")));
// fetch the value property associated with the textbox
String valueInfo = emailTxt.getAttribute("value");
assertEquals(valueInfo, "admin@localhost");
/examples/java/src/test/java/dev/selenium/elements/InformationTest.java
package dev.selenium.elements;
import org.junit.jupiter.api.Test;
import org.openqa.selenium.By;
import org.openqa.selenium.Rectangle;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import java.time.Duration;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
public class InformationTest {
@Test
public void informationWithElements() {
WebDriver driver = new ChromeDriver();
driver.manage().timeouts().implicitlyWait(Duration.ofMillis(500));
// Navigate to Url
driver.get("https://www.selenium.dev/selenium/web/inputs.html");
// isDisplayed
// Get boolean value for is element display
boolean isEmailVisible = driver.findElement(By.name("email_input")).isDisplayed();
assertTrue(isEmailVisible);
// isEnabled
// returns true if element is enabled
boolean isEnabledButton = driver.findElement(By.name("button_input")).isEnabled();
assertTrue(isEnabledButton);
// isSelected
// returns true if element is checked
boolean isSelectedCheck = driver.findElement(By.name("checkbox_input")).isSelected();
assertTrue(isSelectedCheck);
// TagName
// returns TagName of the element
String tagNameInp = driver.findElement(By.name("email_input")).getTagName();
assertEquals("input", tagNameInp);
// GetRect
// Returns height, width, x and y coordinates referenced element
Rectangle res = driver.findElement(By.name("range_input")).getRect();
// Rectangle class provides getX,getY, getWidth, getHeight methods
assertEquals(10, res.getX());
// Retrieves the computed style property 'font-size' of field
String cssValue = driver.findElement(By.name("color_input")).getCssValue("font-size");
assertEquals(cssValue, "13.3333px");
// GetText
// Retrieves the text of the element
String text = driver.findElement(By.tagName("h1")).getText();
assertEquals(text, "Testing Inputs");
// FetchAttributes
// identify the email text box
WebElement emailTxt = driver.findElement(By.name(("email_input")));
// fetch the value property associated with the textbox
String valueInfo = emailTxt.getAttribute("value");
assertEquals(valueInfo, "admin@localhost");
driver.quit();
}
}
# FetchAttributes
email_txt = driver.find_element(By.NAME, "email_input")
value_info = email_txt.get_attribute("value")/examples/python/tests/elements/test_information.py
from selenium import webdriver
from selenium.webdriver.common.by import By
import pytest
def test_informarion():
# Initialize WebDriver
driver = webdriver.Chrome()
driver.implicitly_wait(0.5)
driver.get("https://www.selenium.dev/selenium/web/inputs.html")
# isDisplayed
is_email_visible = driver.find_element(By.NAME, "email_input").is_displayed()
assert is_email_visible == True
# isEnabled
is_enabled_button = driver.find_element(By.NAME, "button_input").is_enabled()
assert is_enabled_button == True
# isSelected
is_selected_check = driver.find_element(By.NAME, "checkbox_input").is_selected()
assert is_selected_check == True
# TagName
tag_name_inp = driver.find_element(By.NAME, "email_input").tag_name
assert tag_name_inp == "input"
# GetRect
rect = driver.find_element(By.NAME, "range_input").rect
assert rect["x"] == 10
# CSS Value
css_value = driver.find_element(By.NAME, "color_input").value_of_css_property(
"font-size"
)
assert css_value == "13.3333px"
# GetText
text = driver.find_element(By.TAG_NAME, "h1").text
assert text == "Testing Inputs"
# FetchAttributes
email_txt = driver.find_element(By.NAME, "email_input")
value_info = email_txt.get_attribute("value")
assert value_info == "admin@localhost"
// FetchAttributes
// identify the email text box
IWebElement emailTxt = driver.FindElement(By.Name("email_input"));
// fetch the value property associated with the textbox
string valueInfo = emailTxt.GetAttribute("value");/examples/dotnet/SeleniumDocs/Elements/InformationTest.cs
using System;
using System.Drawing;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using OpenQA.Selenium;
using OpenQA.Selenium.Chrome;
namespace SeleniumDocs.Elements
{
[TestClass]
public class InformationTest
{
[TestMethod]
public void TestInformationCommands(){
WebDriver driver = new ChromeDriver();
driver.Manage().Timeouts().ImplicitWait = TimeSpan.FromMilliseconds(500);
// Navigate to Url
driver.Url= "https://www.selenium.dev/selenium/web/inputs.html";
// isDisplayed
// Get boolean value for is element display
bool isEmailVisible = driver.FindElement(By.Name("email_input")).Displayed;
Assert.AreEqual(isEmailVisible, true);
// isEnabled
// returns true if element is enabled else returns false
bool isEnabledButton = driver.FindElement(By.Name("button_input")).Enabled;
Assert.AreEqual(isEnabledButton, true);
// isSelected
// returns true if element is checked else returns false
bool isSelectedCheck = driver.FindElement(By.Name("checkbox_input")).Selected;
Assert.AreEqual(isSelectedCheck, true);
// TagName
// returns TagName of the element
string tagNameInp = driver.FindElement(By.Name("email_input")).TagName;
Assert.AreEqual(tagNameInp, "input");
// Get Location and Size
// Get Location
IWebElement rangeElement = driver.FindElement(By.Name("range_input"));
Point point = rangeElement.Location;
Assert.IsNotNull(point.X);
// Get Size
int height=rangeElement.Size.Height;
Assert.IsNotNull(height);
// Retrieves the computed style property 'font-size' of field
string cssValue = driver.FindElement(By.Name("color_input")).GetCssValue("font-size");
Assert.AreEqual(cssValue, "13.3333px");
// GetText
// Retrieves the text of the element
string text = driver.FindElement(By.TagName("h1")).Text;
Assert.AreEqual(text, "Testing Inputs");
// FetchAttributes
// identify the email text box
IWebElement emailTxt = driver.FindElement(By.Name("email_input"));
// fetch the value property associated with the textbox
string valueInfo = emailTxt.GetAttribute("value");
Assert.AreEqual(valueInfo, "admin@localhost");
//Quit the driver
driver.Quit();
}
}
} attribute_value = driver.find_element(name: 'number_input').attribute('value')/examples/ruby/spec/elements/information_spec.rb
# frozen_string_literal: true
require 'spec_helper'
RSpec.describe 'Element Information' do
let(:driver) { start_session }
let(:url) { 'https://www.selenium.dev/selenium/web/inputs.html' }
before { driver.get(url) }
it 'checks if an element is displayed' do
displayed_value = driver.find_element(name: 'email_input').displayed?
expect(displayed_value).to be_truthy
end
it 'checks if an element is enabled' do
enabled_value = driver.find_element(name: 'email_input').enabled?
expect(enabled_value).to be_truthy
end
it 'checks if an element is selected' do
selected_value = driver.find_element(name: 'email_input').selected?
expect(selected_value).to be_falsey
end
it 'gets the tag name of an element' do
tag_name = driver.find_element(name: 'email_input').tag_name
expect(tag_name).not_to be_empty
end
it 'gets the size and position of an element' do
size = driver.find_element(name: 'email_input').size
expect(size.width).to be_positive
expect(size.height).to be_positive
end
it 'gets the css value of an element' do
css_value = driver.find_element(name: 'email_input').css_value('background-color')
expect(css_value).not_to be_empty
end
it 'gets the text of an element' do
text = driver.find_element(xpath: '//h1').text
expect(text).to eq('Testing Inputs')
end
it 'gets the attribute value of an element' do
attribute_value = driver.find_element(name: 'number_input').attribute('value')
expect(attribute_value).not_to be_empty
end
end
// identify the email text box
const emailElement = await driver.findElement(By.xpath('//input[@name="email_input"]'));
//fetch the attribute "name" associated with the textbox
const nameAttribute = await emailElement.getAttribute("name");/examples/javascript/test/elements/information.spec.js
const {By, Builder} = require('selenium-webdriver');
const assert = require("assert");
describe('Element Information Test', function () {
let driver;
before(async function () {
driver = await new Builder().forBrowser('chrome').build();
});
beforeEach(async ()=> {
await driver.get('https://www.selenium.dev/selenium/web/inputs.html');
})
it('Check if element is displayed', async function () {
// Resolves Promise and returns boolean value
let result = await driver.findElement(By.name("email_input")).isDisplayed();
assert.equal(result,true);
});
it('Check if button is enabled', async function () {
// Resolves Promise and returns boolean value
let element = await driver.findElement(By.name("button_input")).isEnabled();
assert.equal(element, true);
});
it('Check if checkbox is selected', async function () {
// Returns true if element is checked else returns false
let isSelected = await driver.findElement(By.name("checkbox_input")).isSelected();
assert.equal(isSelected, true);
});
it('Should return the tagname', async function () {
// Returns TagName of the element
let value = await driver.findElement(By.name('email_input')).getTagName();
assert.equal(value, "input");
});
it('Should be able to fetch element size and position ', async function () {
// Returns height, width, x and y position of the element
let object = await driver.findElement(By.name('range_input')).getRect();
assert.ok(object.height!==null)
assert.ok(object.width!==null)
assert.ok(object.y!==null)
assert.ok(object.x!==null)
});
it('Should be able to fetch attributes and properties ', async function () {
// identify the email text box
const emailElement = await driver.findElement(By.xpath('//input[@name="email_input"]'));
//fetch the attribute "name" associated with the textbox
const nameAttribute = await emailElement.getAttribute("name");
assert.equal(nameAttribute, "email_input")
});
after(async () => await driver.quit());
});
describe('Element Information Test', function () {
let driver;
before(async function () {
driver = await new Builder().forBrowser('chrome').build();
});
it('Should return the css specified CSS value', async function () {
await driver.get('https://www.selenium.dev/selenium/web/colorPage.html');
// Returns background color of the element
let value = await driver.findElement(By.id('namedColor')).getCssValue('background-color');
assert.equal(value, "rgba(0, 128, 0, 1)");
});
it('Should return the css specified CSS value', async function () {
await driver.get('https://www.selenium.dev/selenium/web/linked_image.html');
// Returns text of the element
let text = await driver.findElement(By.id('justanotherLink')).getText();
assert.equal(text, "Just another link.");
});
after(async () => await driver.quit());
});
// Navigate to URL
driver.get("https://www.selenium.dev/selenium/web/inputs.html")
//fetch the value property associated with the textbox
val attr = driver.findElement(By.name("email_input")).getAttribute("value")5 - 文件上传
由于 Selenium 不能与文件上传对话框交互,因此它提供了一种无需打开对话框即可上传文件的方法。
如果该元素是一个类型为 file 的 input 元素,则可以使用
send keys 方法发送将要上传文件的完整路径。
WebElement fileInput = driver.findElement(By.cssSelector("input[type=file]"));
fileInput.sendKeys(uploadFile.getAbsolutePath());
driver.findElement(By.id("file-submit")).click();/examples/java/src/test/java/dev/selenium/elements/FileUploadTest.java
package dev.selenium.elements;
import dev.selenium.BaseChromeTest;
import java.io.File;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import org.openqa.selenium.By;
import org.openqa.selenium.WebElement;
public class FileUploadTest extends BaseChromeTest {
@Test
public void fileUploadTest() {
driver.get("https://the-internet.herokuapp.com/upload");
File uploadFile = new File("src/test/resources/selenium-snapshot.png");
WebElement fileInput = driver.findElement(By.cssSelector("input[type=file]"));
fileInput.sendKeys(uploadFile.getAbsolutePath());
driver.findElement(By.id("file-submit")).click();
WebElement fileName = driver.findElement(By.id("uploaded-files"));
Assertions.assertEquals("selenium-snapshot.png", fileName.getText());
}
}
file_input = driver.find_element(By.CSS_SELECTOR, "input[type='file']")
file_input.send_keys(upload_file)
driver.find_element(By.ID, "file-submit").click()/examples/python/tests/elements/test_file_upload.py
import os
from selenium import webdriver
from selenium.webdriver.common.by import By
def test_uploads(driver):
driver.get("https://the-internet.herokuapp.com/upload")
upload_file = os.path.abspath(
os.path.join(os.path.dirname(__file__), "..", "selenium-snapshot.png"))
file_input = driver.find_element(By.CSS_SELECTOR, "input[type='file']")
file_input.send_keys(upload_file)
driver.find_element(By.ID, "file-submit").click()
file_name_element = driver.find_element(By.ID, "uploaded-files")
file_name = file_name_element.text
assert file_name == "selenium-snapshot.png"
IWebElement fileInput = driver.FindElement(By.CssSelector("input[type=file]"));
fileInput.SendKeys(uploadFile);
driver.FindElement(By.Id("file-submit")).Click();/examples/dotnet/SeleniumDocs/Elements/FileUploadTest.cs
using System;
using System.IO;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using OpenQA.Selenium;
namespace SeleniumDocs.Elements
{
[TestClass]
public class FileUploadTest : BaseChromeTest
{
[TestMethod]
public void Uploads()
{
driver.Url = "https://the-internet.herokuapp.com/upload";
string baseDirectory = AppContext.BaseDirectory;
string relativePath = "../../../TestSupport/selenium-snapshot.png";
string uploadFile = Path.GetFullPath(Path.Combine(baseDirectory, relativePath));
IWebElement fileInput = driver.FindElement(By.CssSelector("input[type=file]"));
fileInput.SendKeys(uploadFile);
driver.FindElement(By.Id("file-submit")).Click();
var fileName = new OpenQA.Selenium.Support.UI.WebDriverWait(driver, TimeSpan.FromSeconds(5)).Until(d => d.FindElement(By.Id("uploaded-files")));
Assert.AreEqual("selenium-snapshot.png", fileName.Text);
}
}
} file_input = driver.find_element(css: 'input[type=file]')
file_input.send_keys(upload_file)
driver.find_element(id: 'file-submit').click/examples/ruby/spec/elements/file_upload_spec.rb
# frozen_string_literal: true
require 'spec_helper'
RSpec.describe 'File Upload' do
let(:driver) { start_session }
it 'uploads' do
driver.get('https://the-internet.herokuapp.com/upload')
upload_file = File.expand_path('../spec_support/selenium-snapshot.png', __dir__)
file_input = driver.find_element(css: 'input[type=file]')
file_input.send_keys(upload_file)
driver.find_element(id: 'file-submit').click
file_name = driver.find_element(id: 'uploaded-files')
expect(file_name.text).to eq 'selenium-snapshot.png'
end
end
await driver.get('https://the-internet.herokuapp.com/upload');
// Upload snapshot
/examples/javascript/test/elements/fileUpload.spec.js
const {Browser, By, until, Builder} = require("selenium-webdriver");
const path = require("path");
const assert = require('node:assert');
describe('File Upload Test', function() {
let driver;
before(async function() {
driver = new Builder()
.forBrowser(Browser.CHROME)
.build();
});
after(async() => await driver.quit());
it('Should be able to upload a file successfully', async function() {
const image = path.resolve('./test/resources/selenium-snapshot.png')
await driver.manage().setTimeouts({implicit: 5000});
// Navigate to URL
await driver.get('https://the-internet.herokuapp.com/upload');
// Upload snapshot
await driver.findElement(By.id("file-upload")).sendKeys(image);
await driver.findElement(By.id("file-submit")).submit();
const revealed = await driver.findElement(By.id('uploaded-files'))
await driver.wait(until.elementIsVisible(revealed), 2000);
const data = await driver.findElement(By.css('h3'));
assert.equal(await data.getText(), `File Uploaded!`);
});
});



