The majority of most people’s Selenium code involves working with web elements.
This is the multi-page printable view of this section. Click here to print.
Web elements
- 1: File Upload
- 2: Locator strategies
- 3: Finding web elements
- 4: Interacting with web elements
- 5: Information about web elements
1 - File Upload
Because Selenium cannot interact with the file upload dialog, it provides a way
to upload files without opening the dialog. If the element is an input
element with type file
,
you can use the send keys method to send the full path to the file that will be uploaded.
WebElement fileInput = driver.findElement(By.cssSelector("input[type=file]"));
fileInput.sendKeys(uploadFile.getAbsolutePath());
driver.findElement(By.id("file-submit")).click();
Show full example
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()
Show full example
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();
Show full example
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();
IWebElement fileName = driver.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
Show full example
# 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
Show full example
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!`);
});
});
2 - Locator strategies
A locator is a way to identify elements on a page. It is the argument passed to the Finding element methods.
Check out our encouraged test practices for tips on locators, including which to use when and why to declare locators separately from the finding methods.
Traditional Locators
Selenium provides support for these 8 traditional location strategies in WebDriver:
Locator | Description |
---|---|
class name | Locates elements whose class name contains the search value (compound class names are not permitted) |
css selector | Locates elements matching a CSS selector |
id | Locates elements whose ID attribute matches the search value |
name | Locates elements whose NAME attribute matches the search value |
link text | Locates anchor elements whose visible text matches the search value |
partial link text | Locates anchor elements whose visible text contains the search value. If multiple elements are matching, only the first one will be selected. |
tag name | Locates elements whose tag name matches the search value |
xpath | Locates elements matching an XPath expression |
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.
WebDriver driver = new ChromeDriver();
driver.findElement(By.className("information"));
driver = webdriver.Chrome()
driver.get("https://www.selenium.dev/selenium/web/locators_tests/locators.html")
element = driver.find_element(By.CLASS_NAME, "information")
Show full example
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')
Show full example
# 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.
WebDriver driver = new ChromeDriver();
driver.findElement(By.cssSelector("#fname"));
driver = webdriver.Chrome()
driver.get("https://www.selenium.dev/selenium/web/locators_tests/locators.html")
element = driver.find_element(By.CSS_SELECTOR, "#fname")
Show full example
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')
Show full example
# 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 of an element in a web page to locate it. Generally the ID property should be unique for each element on the web page. We will identify the Last Name field using it.
WebDriver driver = new ChromeDriver();
driver.findElement(By.id("lname"));
driver = webdriver.Chrome()
driver.get("https://www.selenium.dev/selenium/web/locators_tests/locators.html")
element = driver.find_element(By.ID, "lname")
Show full example
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')
Show full example
# 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 of an element in a web page to locate it. Generally the NAME property should be unique for each element on the web page. We will identify the Newsletter checkbox using it.
WebDriver driver = new ChromeDriver();
driver.findElement(By.name("newsletter"));
driver = webdriver.Chrome()
driver.get("https://www.selenium.dev/selenium/web/locators_tests/locators.html")
element = driver.find_element(By.NAME, "newsletter")
Show full example
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')
Show full example
# 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, let’s see how will we locate it.
WebDriver driver = new ChromeDriver();
driver.findElement(By.linkText("Selenium Official Page"));
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")
Show full example
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')
Show full example
# 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.
WebDriver driver = new ChromeDriver();
driver.findElement(By.partialLinkText("Official Page"));
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")
Show full example
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')
Show full example
# 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”.
WebDriver driver = new ChromeDriver();
driver.findElement(By.tagName("a"));
driver = webdriver.Chrome()
driver.get("https://www.selenium.dev/selenium/web/locators_tests/locators.html")
element = driver.find_element(By.TAG_NAME, "a")
Show full example
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')
Show full example
# 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.
WebDriver driver = new ChromeDriver();
driver.findElement(By.xpath("//input[@value='f']"));
driver = webdriver.Chrome()
driver.get("https://www.selenium.dev/selenium/web/locators_tests/locators.html")
element = driver.find_element(By.XPATH, "//input[@value='f']")
Show full example
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']")
Show full example
# 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']'));
import org.openqa.selenium.By
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')
Show full example
# 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 example = new ByChained(By.id("login-form"), By.id("username-field"));
WebElement username_input = driver.findElement(example);
Show full example
package dev.selenium.elements;
import org.openqa.selenium.By;
import org.openqa.selenium.support.pagefactory.ByAll;
import org.openqa.selenium.support.pagefactory.ByChained;
import dev.selenium.BaseTest;
import java.util.List;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
public class LocatorsTest extends BaseTest {
public void ByAllTest() {
// Create instance of ChromeDriver
WebDriver driver = new ChromeDriver();
// Navigate to Url
driver.get("https://www.selenium.dev/selenium/web/login.html");
// get both logins
By example = new ByAll(By.id("password-field"), By.id("username-field"));
List<WebElement> login_inputs = driver.findElements(example);
//send them both input
login_inputs.get(0).sendKeys("username");
login_inputs.get(1).sendKeys("password");
}
public String ByChainedTest() {
// Create instance of ChromeDriver
WebDriver driver = new ChromeDriver();
// Navigate to Url
driver.get("https://www.selenium.dev/selenium/web/login.html");
// Find username-field inside of login-form
By example = new ByChained(By.id("login-form"), By.id("username-field"));
WebElement username_input = driver.findElement(example);
//return placeholder text
String placeholder = username_input.getAttribute("placeholder");
return placeholder;
}
}
ByAll
The ByAll
class enables you to utilize two By locators at once, finding elements that mach either of your By locators.
For example, instead of having to utilize two FindElement()
functions to find the username and password input fields
seperately, you can instead find them together in one clean FindElements()
By example = new ByAll(By.id("password-field"), By.id("username-field"));
List<WebElement> login_inputs = driver.findElements(example);
Show full example
package dev.selenium.elements;
import org.openqa.selenium.By;
import org.openqa.selenium.support.pagefactory.ByAll;
import org.openqa.selenium.support.pagefactory.ByChained;
import dev.selenium.BaseTest;
import java.util.List;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
public class LocatorsTest extends BaseTest {
public void ByAllTest() {
// Create instance of ChromeDriver
WebDriver driver = new ChromeDriver();
// Navigate to Url
driver.get("https://www.selenium.dev/selenium/web/login.html");
// get both logins
By example = new ByAll(By.id("password-field"), By.id("username-field"));
List<WebElement> login_inputs = driver.findElements(example);
//send them both input
login_inputs.get(0).sendKeys("username");
login_inputs.get(1).sendKeys("password");
}
public String ByChainedTest() {
// Create instance of ChromeDriver
WebDriver driver = new ChromeDriver();
// Navigate to Url
driver.get("https://www.selenium.dev/selenium/web/login.html");
// Find username-field inside of login-form
By example = new ByChained(By.id("login-form"), By.id("username-field"));
WebElement username_input = driver.findElement(example);
//return placeholder text
String placeholder = username_input.getAttribute("placeholder");
return placeholder;
}
}
Relative Locators
Selenium 4 introduces Relative Locators (previously called 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.
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'}}})
Show full example
# 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'}}})
Show full example
# 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'}}})
Show full example
# 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'}}})
Show full example
# 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'}}})
Show full example
# 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'}}})
Show full example
# 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"))
3 - Finding web elements
One of the most fundamental aspects of using Selenium is obtaining element references to work with. Selenium offers a number of built-in locator strategies to uniquely identify an element. There are many ways to use the locators in very advanced scenarios. For the purposes of this documentation, let’s consider this HTML snippet:
<ol id="vegetables">
<li class="potatoes">…
<li class="onions">…
<li class="tomatoes"><span>Tomato is a Vegetable</span>…
</ol>
<ul id="fruits">
<li class="bananas">…
<li class="apples">…
<li class="tomatoes"><span>Tomato is a Fruit</span>…
</ul>
First matching element
Many locators will match multiple elements on the page. The singular find element method will return a reference to the first element found within a given context.
Evaluating entire DOM
When the find element method is called on the driver instance, it returns a reference to the first element in the DOM that matches with the provided locator. This value can be stored and used for future element actions. In our example HTML above, there are two elements that have a class name of “tomatoes” so this method will return the element in the “vegetables” list.
WebElement vegetable = driver.findElement(By.className("tomatoes"));
vegetable = driver.find_element(By.CLASS_NAME, "tomatoes")
var vegetable = driver.FindElement(By.ClassName("tomatoes"));
fruits = driver.find_element(id: 'fruits')
fruits.find_element(class: 'tomatoes')
Show full example
# frozen_string_literal: true
require 'spec_helper'
RSpec.describe 'Element Finders' do
let(:driver) { start_session }
context 'without executing finders', skip: 'these are just examples, not actual tests' do
it 'finds the first matching element' do
driver.find_element(class: 'tomatoes')
end
it 'uses a subset of the dom to find an element' do
fruits = driver.find_element(id: 'fruits')
fruits.find_element(class: 'tomatoes')
end
it 'uses an optimized locator' do
driver.find_element(css: '#fruits .tomatoes')
end
it 'finds all matching elements' do
driver.find_elements(tag_name: 'li')
end
it 'gets an element from a collection' do
elements = driver.find_elements(:tag_name, 'p')
elements.each { |e| puts e.text }
end
it 'finds element from element' do
element = driver.find_element(:tag_name, 'div')
elements = element.find_elements(:tag_name, 'p')
elements.each { |e| puts e.text }
end
it 'find active element' do
driver.find_element(css: '[name="q"]').send_keys('webElement')
driver.switch_to.active_element.attribute('title')
end
end
end
const vegetable = await driver.findElement(By.className('tomatoes'));
val vegetable: WebElement = driver.findElement(By.className("tomatoes"))
Evaluating a subset of the DOM
Rather than finding a unique locator in the entire DOM, it is often useful to narrow the search to the scope of another located element. In the above example there are two elements with a class name of “tomatoes” and it is a little more challenging to get the reference for the second one.
One solution is to locate an element with a unique attribute that is an ancestor of the desired element and not an ancestor of the undesired element, then call find element on that object:
WebElement fruits = driver.findElement(By.id("fruits"));
WebElement fruit = fruits.findElement(By.className("tomatoes"));
fruits = driver.find_element(By.ID, "fruits")
fruit = fruits.find_element(By.CLASS_NAME,"tomatoes")
IWebElement fruits = driver.FindElement(By.Id("fruits"));
IWebElement fruit = fruits.FindElement(By.ClassName("tomatoes"));
fruits = driver.find_element(id: 'fruits')
fruits.find_element(class: 'tomatoes')
Show full example
# frozen_string_literal: true
require 'spec_helper'
RSpec.describe 'Element Finders' do
let(:driver) { start_session }
context 'without executing finders', skip: 'these are just examples, not actual tests' do
it 'finds the first matching element' do
driver.find_element(class: 'tomatoes')
end
it 'uses a subset of the dom to find an element' do
fruits = driver.find_element(id: 'fruits')
fruits.find_element(class: 'tomatoes')
end
it 'uses an optimized locator' do
driver.find_element(css: '#fruits .tomatoes')
end
it 'finds all matching elements' do
driver.find_elements(tag_name: 'li')
end
it 'gets an element from a collection' do
elements = driver.find_elements(:tag_name, 'p')
elements.each { |e| puts e.text }
end
it 'finds element from element' do
element = driver.find_element(:tag_name, 'div')
elements = element.find_elements(:tag_name, 'p')
elements.each { |e| puts e.text }
end
it 'find active element' do
driver.find_element(css: '[name="q"]').send_keys('webElement')
driver.switch_to.active_element.attribute('title')
end
end
end
const fruits = await driver.findElement(By.id('fruits'));
const fruit = fruits.findElement(By.className('tomatoes'));
val fruits = driver.findElement(By.id("fruits"))
val fruit = fruits.findElement(By.className("tomatoes"))
Java and C#WebDriver
, WebElement
and ShadowRoot
classes all implement a SearchContext
interface, which is
considered a role-based interface. Role-based interfaces allow you to determine whether a particular
driver implementation supports a given feature. These interfaces are clearly defined and try
to adhere to having only a single role of responsibility.
Evaluating the Shadow DOM
The Shadow DOM is an encapsulated DOM tree hidden inside an element. With the release of v96 in Chromium Browsers, Selenium can now allow you to access this tree with easy-to-use shadow root methods. NOTE: These methods require Selenium 4.0 or greater.
WebElement shadowHost = driver.findElement(By.cssSelector("#shadow_host"));
SearchContext shadowRoot = shadowHost.getShadowRoot();
WebElement shadowContent = shadowRoot.findElement(By.cssSelector("#shadow_content"));
shadow_host = driver.find_element(By.CSS_SELECTOR, '#shadow_host')
shadow_root = shadow_host.shadow_root
shadow_content = shadow_root.find_element(By.CSS_SELECTOR, '#shadow_content')
var shadowHost = _driver.FindElement(By.CssSelector("#shadow_host"));
var shadowRoot = shadowHost.GetShadowRoot();
var shadowContent = shadowRoot.FindElement(By.CssSelector("#shadow_content"));
shadow_host = @driver.find_element(css: '#shadow_host')
shadow_root = shadow_host.shadow_root
shadow_content = shadow_root.find_element(css: '#shadow_content')
Optimized locator
A nested lookup might not be the most effective location strategy since it requires two separate commands to be issued to the browser.
To improve the performance slightly, we can use either CSS or XPath to find this element in a single command. See the Locator strategy suggestions in our Encouraged test practices section.
For this example, we’ll use a CSS Selector:
WebElement fruit = driver.findElement(By.cssSelector("#fruits .tomatoes"));
fruit = driver.find_element(By.CSS_SELECTOR,"#fruits .tomatoes")
var fruit = driver.FindElement(By.CssSelector("#fruits .tomatoes"));
driver.find_element(css: '#fruits .tomatoes')
Show full example
# frozen_string_literal: true
require 'spec_helper'
RSpec.describe 'Element Finders' do
let(:driver) { start_session }
context 'without executing finders', skip: 'these are just examples, not actual tests' do
it 'finds the first matching element' do
driver.find_element(class: 'tomatoes')
end
it 'uses a subset of the dom to find an element' do
fruits = driver.find_element(id: 'fruits')
fruits.find_element(class: 'tomatoes')
end
it 'uses an optimized locator' do
driver.find_element(css: '#fruits .tomatoes')
end
it 'finds all matching elements' do
driver.find_elements(tag_name: 'li')
end
it 'gets an element from a collection' do
elements = driver.find_elements(:tag_name, 'p')
elements.each { |e| puts e.text }
end
it 'finds element from element' do
element = driver.find_element(:tag_name, 'div')
elements = element.find_elements(:tag_name, 'p')
elements.each { |e| puts e.text }
end
it 'find active element' do
driver.find_element(css: '[name="q"]').send_keys('webElement')
driver.switch_to.active_element.attribute('title')
end
end
end
const fruit = await driver.findElement(By.css('#fruits .tomatoes'));
val fruit = driver.findElement(By.cssSelector("#fruits .tomatoes"))
All matching elements
There are several use cases for needing to get references to all elements that match a locator, rather than just the first one. The plural find elements methods return a collection of element references. If there are no matches, an empty list is returned. In this case, references to all fruits and vegetable list items will be returned in a collection.
List<WebElement> plants = driver.findElements(By.tagName("li"));
plants = driver.find_elements(By.TAG_NAME, "li")
IReadOnlyList<IWebElement> plants = driver.FindElements(By.TagName("li"));
driver.find_elements(tag_name: 'li')
Show full example
# frozen_string_literal: true
require 'spec_helper'
RSpec.describe 'Element Finders' do
let(:driver) { start_session }
context 'without executing finders', skip: 'these are just examples, not actual tests' do
it 'finds the first matching element' do
driver.find_element(class: 'tomatoes')
end
it 'uses a subset of the dom to find an element' do
fruits = driver.find_element(id: 'fruits')
fruits.find_element(class: 'tomatoes')
end
it 'uses an optimized locator' do
driver.find_element(css: '#fruits .tomatoes')
end
it 'finds all matching elements' do
driver.find_elements(tag_name: 'li')
end
it 'gets an element from a collection' do
elements = driver.find_elements(:tag_name, 'p')
elements.each { |e| puts e.text }
end
it 'finds element from element' do
element = driver.find_element(:tag_name, 'div')
elements = element.find_elements(:tag_name, 'p')
elements.each { |e| puts e.text }
end
it 'find active element' do
driver.find_element(css: '[name="q"]').send_keys('webElement')
driver.switch_to.active_element.attribute('title')
end
end
end
const plants = await driver.findElements(By.tagName('li'));
val plants: List<WebElement> = driver.findElements(By.tagName("li"))
Get element
Often you get a collection of elements but want to work with a specific element, which means you need to iterate over the collection and identify the one you want.
List<WebElement> elements = driver.findElements(By.tagName("li"));
for (WebElement element : elements) {
System.out.println("Paragraph text:" + element.getText());
}
from selenium import webdriver
from selenium.webdriver.common.by import By
driver = webdriver.Firefox()
# Navigate to Url
driver.get("https://www.example.com")
# Get all the elements available with tag name 'p'
elements = driver.find_elements(By.TAG_NAME, 'p')
for e in elements:
print(e.text)
using OpenQA.Selenium;
using OpenQA.Selenium.Firefox;
using System.Collections.Generic;
namespace FindElementsExample {
class FindElementsExample {
public static void Main(string[] args) {
IWebDriver driver = new FirefoxDriver();
try {
// Navigate to Url
driver.Navigate().GoToUrl("https://example.com");
// Get all the elements available with tag name 'p'
IList < IWebElement > elements = driver.FindElements(By.TagName("p"));
foreach(IWebElement e in elements) {
System.Console.WriteLine(e.Text);
}
} finally {
driver.Quit();
}
}
}
}
elements = driver.find_elements(:tag_name, 'p')
elements.each { |e| puts e.text }
Show full example
# frozen_string_literal: true
require 'spec_helper'
RSpec.describe 'Element Finders' do
let(:driver) { start_session }
context 'without executing finders', skip: 'these are just examples, not actual tests' do
it 'finds the first matching element' do
driver.find_element(class: 'tomatoes')
end
it 'uses a subset of the dom to find an element' do
fruits = driver.find_element(id: 'fruits')
fruits.find_element(class: 'tomatoes')
end
it 'uses an optimized locator' do
driver.find_element(css: '#fruits .tomatoes')
end
it 'finds all matching elements' do
driver.find_elements(tag_name: 'li')
end
it 'gets an element from a collection' do
elements = driver.find_elements(:tag_name, 'p')
elements.each { |e| puts e.text }
end
it 'finds element from element' do
element = driver.find_element(:tag_name, 'div')
elements = element.find_elements(:tag_name, 'p')
elements.each { |e| puts e.text }
end
it 'find active element' do
driver.find_element(css: '[name="q"]').send_keys('webElement')
driver.switch_to.active_element.attribute('title')
end
end
end
const {Builder, By} = require('selenium-webdriver');
(async function example() {
let driver = await new Builder().forBrowser('firefox').build();
try {
// Navigate to Url
await driver.get('https://www.example.com');
// Get all the elements available with tag 'p'
let elements = await driver.findElements(By.css('p'));
for(let e of elements) {
console.log(await e.getText());
}
}
finally {
await driver.quit();
}
})();
import org.openqa.selenium.By
import org.openqa.selenium.firefox.FirefoxDriver
fun main() {
val driver = FirefoxDriver()
try {
driver.get("https://example.com")
// Get all the elements available with tag name 'p'
val elements = driver.findElements(By.tagName("p"))
for (element in elements) {
println("Paragraph text:" + element.text)
}
} finally {
driver.quit()
}
}
Find Elements From Element
It is used to find the list of matching child WebElements within the context of parent element. To achieve this, the parent WebElement is chained with ‘findElements’ to access child elements
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import java.util.List;
public class findElementsFromElement {
public static void main(String[] args) {
WebDriver driver = new ChromeDriver();
try {
driver.get("https://example.com");
// Get element with tag name 'div'
WebElement element = driver.findElement(By.tagName("div"));
// Get all the elements available with tag name 'p'
List<WebElement> elements = element.findElements(By.tagName("p"));
for (WebElement e : elements) {
System.out.println(e.getText());
}
} finally {
driver.quit();
}
}
}
from selenium import webdriver
from selenium.webdriver.common.by import By
driver = webdriver.Chrome()
driver.get("https://www.example.com")
##get elements from parent element using TAG_NAME
# Get element with tag name 'div'
element = driver.find_element(By.TAG_NAME, 'div')
# Get all the elements available with tag name 'p'
elements = element.find_elements(By.TAG_NAME, 'p')
for e in elements:
print(e.text)
##get elements from parent element using XPATH
##NOTE: in order to utilize XPATH from current element, you must add "." to beginning of path
# Get first element of tag 'ul'
element = driver.find_element(By.XPATH, '//ul')
# get children of tag 'ul' with tag 'li'
elements = driver.find_elements(By.XPATH, './/li')
for e in elements:
print(e.text)
using OpenQA.Selenium;
using OpenQA.Selenium.Chrome;
using System.Collections.Generic;
namespace FindElementsFromElement {
class FindElementsFromElement {
public static void Main(string[] args) {
IWebDriver driver = new ChromeDriver();
try {
driver.Navigate().GoToUrl("https://example.com");
// Get element with tag name 'div'
IWebElement element = driver.FindElement(By.TagName("div"));
// Get all the elements available with tag name 'p'
IList < IWebElement > elements = element.FindElements(By.TagName("p"));
foreach(IWebElement e in elements) {
System.Console.WriteLine(e.Text);
}
} finally {
driver.Quit();
}
}
}
}
element = driver.find_element(:tag_name, 'div')
elements = element.find_elements(:tag_name, 'p')
elements.each { |e| puts e.text }
Show full example
# frozen_string_literal: true
require 'spec_helper'
RSpec.describe 'Element Finders' do
let(:driver) { start_session }
context 'without executing finders', skip: 'these are just examples, not actual tests' do
it 'finds the first matching element' do
driver.find_element(class: 'tomatoes')
end
it 'uses a subset of the dom to find an element' do
fruits = driver.find_element(id: 'fruits')
fruits.find_element(class: 'tomatoes')
end
it 'uses an optimized locator' do
driver.find_element(css: '#fruits .tomatoes')
end
it 'finds all matching elements' do
driver.find_elements(tag_name: 'li')
end
it 'gets an element from a collection' do
elements = driver.find_elements(:tag_name, 'p')
elements.each { |e| puts e.text }
end
it 'finds element from element' do
element = driver.find_element(:tag_name, 'div')
elements = element.find_elements(:tag_name, 'p')
elements.each { |e| puts e.text }
end
it 'find active element' do
driver.find_element(css: '[name="q"]').send_keys('webElement')
driver.switch_to.active_element.attribute('title')
end
end
end
const {Builder, By} = require('selenium-webdriver');
(async function example() {
let driver = new Builder()
.forBrowser('chrome')
.build();
await driver.get('https://www.example.com');
// Get element with tag name 'div'
let element = driver.findElement(By.css("div"));
// Get all the elements available with tag name 'p'
let elements = await element.findElements(By.css("p"));
for(let e of elements) {
console.log(await e.getText());
}
})();
import org.openqa.selenium.By
import org.openqa.selenium.chrome.ChromeDriver
fun main() {
val driver = ChromeDriver()
try {
driver.get("https://example.com")
// Get element with tag name 'div'
val element = driver.findElement(By.tagName("div"))
// Get all the elements available with tag name 'p'
val elements = element.findElements(By.tagName("p"))
for (e in elements) {
println(e.text)
}
} finally {
driver.quit()
}
}
Get Active Element
It is used to track (or) find DOM element which has the focus in the current browsing context.
import org.openqa.selenium.*;
import org.openqa.selenium.chrome.ChromeDriver;
public class activeElementTest {
public static void main(String[] args) {
WebDriver driver = new ChromeDriver();
try {
driver.get("http://www.google.com");
driver.findElement(By.cssSelector("[name='q']")).sendKeys("webElement");
// Get attribute of current active element
String attr = driver.switchTo().activeElement().getAttribute("title");
System.out.println(attr);
} finally {
driver.quit();
}
}
}
from selenium import webdriver
from selenium.webdriver.common.by import By
driver = webdriver.Chrome()
driver.get("https://www.google.com")
driver.find_element(By.CSS_SELECTOR, '[name="q"]').send_keys("webElement")
# Get attribute of current active element
attr = driver.switch_to.active_element.get_attribute("title")
print(attr)
using OpenQA.Selenium;
using OpenQA.Selenium.Chrome;
namespace ActiveElement {
class ActiveElement {
public static void Main(string[] args) {
IWebDriver driver = new ChromeDriver();
try {
// Navigate to Url
driver.Navigate().GoToUrl("https://www.google.com");
driver.FindElement(By.CssSelector("[name='q']")).SendKeys("webElement");
// Get attribute of current active element
string attr = driver.SwitchTo().ActiveElement().GetAttribute("title");
System.Console.WriteLine(attr);
} finally {
driver.Quit();
}
}
}
}
driver.find_element(css: '[name="q"]').send_keys('webElement')
driver.switch_to.active_element.attribute('title')
Show full example
# frozen_string_literal: true
require 'spec_helper'
RSpec.describe 'Element Finders' do
let(:driver) { start_session }
context 'without executing finders', skip: 'these are just examples, not actual tests' do
it 'finds the first matching element' do
driver.find_element(class: 'tomatoes')
end
it 'uses a subset of the dom to find an element' do
fruits = driver.find_element(id: 'fruits')
fruits.find_element(class: 'tomatoes')
end
it 'uses an optimized locator' do
driver.find_element(css: '#fruits .tomatoes')
end
it 'finds all matching elements' do
driver.find_elements(tag_name: 'li')
end
it 'gets an element from a collection' do
elements = driver.find_elements(:tag_name, 'p')
elements.each { |e| puts e.text }
end
it 'finds element from element' do
element = driver.find_element(:tag_name, 'div')
elements = element.find_elements(:tag_name, 'p')
elements.each { |e| puts e.text }
end
it 'find active element' do
driver.find_element(css: '[name="q"]').send_keys('webElement')
driver.switch_to.active_element.attribute('title')
end
end
end
const {Builder, By} = require('selenium-webdriver');
(async function example() {
let driver = await new Builder().forBrowser('chrome').build();
await driver.get('https://www.google.com');
await driver.findElement(By.css('[name="q"]')).sendKeys("webElement");
// Get attribute of current active element
let attr = await driver.switchTo().activeElement().getAttribute("title");
console.log(`${attr}`)
})();
import org.openqa.selenium.By
import org.openqa.selenium.chrome.ChromeDriver
fun main() {
val driver = ChromeDriver()
try {
driver.get("https://www.google.com")
driver.findElement(By.cssSelector("[name='q']")).sendKeys("webElement")
// Get attribute of current active element
val attr = driver.switchTo().activeElement().getAttribute("title")
print(attr)
} finally {
driver.quit()
}
}
4 - Interacting with web elements
There are only 5 basic commands that can be executed on an element:
- click (applies to any element)
- send keys (only applies to text fields and content editable elements)
- clear (only applies to text fields and content editable elements)
- submit (only applies to form elements)
- select (see Select List Elements)
Additional validations
These methods are designed to closely emulate a user’s experience, so, unlike the Actions API, it attempts to perform two things before attempting the specified action.
- If it determines the element is outside the viewport, it scrolls the element into view, specifically it will align the bottom of the element with the bottom of the viewport.
- It ensures the element is interactable before taking the action. This could mean that the scrolling was unsuccessful, or that the element is not otherwise displayed. Determining if an element is displayed on a page was too difficult to define directly in the webdriver specification, so Selenium sends an execute command with a JavaScript atom that checks for things that would keep the element from being displayed. If it determines an element is not in the viewport, not displayed, not keyboard-interactable, or not pointer-interactable, it returns an element not interactable error.
Click
The element click command is executed on the center of the element. If the center of the element is obscured for some reason, Selenium will return an element click intercepted error.
driver.get("https://www.selenium.dev/selenium/web/inputs.html");
// Click on the element
WebElement checkInput=driver.findElement(By.name("checkbox_input"));
checkInput.click();
Show full example
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()
Show full example
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();
Show full example
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
Show full example
# 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();
Show full example
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();
Send keys
The element send keys command
types the provided keys into an editable element.
Typically, this means an element is an input element of a form with a text
type or an element
with a content-editable
attribute. If it is not editable,
an invalid element state error is returned.
Here is the list of possible keystrokes that WebDriver Supports.
// 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);
Show full example
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
Show full example
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);
Show full example
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'
Show full example
# 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'));
Show full example
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
The element clear command resets the content of an element.
This requires an element to be editable,
and resettable. Typically,
this means an element is an input element of a form with a text
type or an element
with acontent-editable
attribute. If these conditions are not met,
an invalid element state error is returned.
//Clear Element
// Clear field to empty it from any previous data
emailInput.clear();
Show full example
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()
Show full example
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");
Show full example
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
Show full example
# 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');
Show full example
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()
Submit
In Selenium 4 this is no longer implemented with a separate endpoint and functions by executing a script. As such, it is recommended not to use this method and to click the applicable form submission button instead.
5 - Information about web elements
There are a number of details you can query about a specific element.
Is Displayed
This method is used to check if the connected Element is
displayed on a webpage. Returns a Boolean
value,
True if the connected element is displayed in the current
browsing context else returns false.
This functionality is mentioned in, but not defined by the w3c specification due to the impossibility of covering all potential conditions. As such, Selenium cannot expect drivers to implement this functionality directly, and now relies on executing a large JavaScript function directly. This function makes many approximations about an element’s nature and relationship in the tree to return a value.
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();
Show full example
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;
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();
assertEquals(isEmailVisible,true);
// isEnabled
// returns true if element is enabled else returns false
boolean isEnabledButton = driver.findElement(By.name("button_input")).isEnabled();
assertEquals(isEnabledButton,true);
// isSelected
// returns true if element is checked else returns false
boolean isSelectedCheck = driver.findElement(By.name("checkbox_input")).isSelected();
assertEquals(isSelectedCheck,true);
// TagName
// returns TagName of the element
String tagNameInp = driver.findElement(By.name("email_input")).getTagName();
assertEquals(tagNameInp,"input");
// 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(res.getX(),10);
// 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()
Show full example
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;
Show full example
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?
Show full example
# 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();
Show full example
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 ins 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()
Is Enabled
This method is used to check if the connected Element is enabled or disabled on a webpage. Returns a boolean value, True if the connected element is enabled in the current browsing context else returns false.
// isEnabled
// returns true if element is enabled else returns false
boolean isEnabledButton = driver.findElement(By.name("button_input")).isEnabled();
Show full example
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;
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();
assertEquals(isEmailVisible,true);
// isEnabled
// returns true if element is enabled else returns false
boolean isEnabledButton = driver.findElement(By.name("button_input")).isEnabled();
assertEquals(isEnabledButton,true);
// isSelected
// returns true if element is checked else returns false
boolean isSelectedCheck = driver.findElement(By.name("checkbox_input")).isSelected();
assertEquals(isSelectedCheck,true);
// TagName
// returns TagName of the element
String tagNameInp = driver.findElement(By.name("email_input")).getTagName();
assertEquals(tagNameInp,"input");
// 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(res.getX(),10);
// 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()
Show full example
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;
Show full example
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?
Show full example
# 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();
Show full example
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 ins 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()
Is Selected
This method determines if the referenced Element is Selected or not. This method is widely used on Check boxes, radio buttons, input elements, and option elements.
Returns a boolean value, True if referenced element is selected in the current browsing context else returns false.
// isSelected
// returns true if element is checked else returns false
boolean isSelectedCheck = driver.findElement(By.name("checkbox_input")).isSelected();
Show full example
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;
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();
assertEquals(isEmailVisible,true);
// isEnabled
// returns true if element is enabled else returns false
boolean isEnabledButton = driver.findElement(By.name("button_input")).isEnabled();
assertEquals(isEnabledButton,true);
// isSelected
// returns true if element is checked else returns false
boolean isSelectedCheck = driver.findElement(By.name("checkbox_input")).isSelected();
assertEquals(isSelectedCheck,true);
// TagName
// returns TagName of the element
String tagNameInp = driver.findElement(By.name("email_input")).getTagName();
assertEquals(tagNameInp,"input");
// 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(res.getX(),10);
// 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()
Show full example
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;
Show full example
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?
Show full example
# 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 ins checked else returns false
let isSelected = await driver.findElement(By.name("checkbox_input")).isSelected();
Show full example
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 ins 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()
Tag Name
It is used to fetch the TagName of the referenced Element which has the focus in the current browsing context.
// TagName
// returns TagName of the element
String tagNameInp = driver.findElement(By.name("email_input")).getTagName();
Show full example
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;
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();
assertEquals(isEmailVisible,true);
// isEnabled
// returns true if element is enabled else returns false
boolean isEnabledButton = driver.findElement(By.name("button_input")).isEnabled();
assertEquals(isEnabledButton,true);
// isSelected
// returns true if element is checked else returns false
boolean isSelectedCheck = driver.findElement(By.name("checkbox_input")).isSelected();
assertEquals(isSelectedCheck,true);
// TagName
// returns TagName of the element
String tagNameInp = driver.findElement(By.name("email_input")).getTagName();
assertEquals(tagNameInp,"input");
// 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(res.getX(),10);
// 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
Show full example
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;
Show full example
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
Show full example
# 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();
Show full example
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 ins 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()
Size and Position
It is used to fetch the dimensions and coordinates of the referenced element.
The fetched data body contain the following details:
- X-axis position from the top-left corner of the element
- y-axis position from the top-left corner of the element
- Height of the element
- Width of the element
// GetRect
// Returns height, width, x and y coordinates referenced element
Rectangle res = driver.findElement(By.name("range_input")).getRect();
Show full example
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;
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();
assertEquals(isEmailVisible,true);
// isEnabled
// returns true if element is enabled else returns false
boolean isEnabledButton = driver.findElement(By.name("button_input")).isEnabled();
assertEquals(isEnabledButton,true);
// isSelected
// returns true if element is checked else returns false
boolean isSelectedCheck = driver.findElement(By.name("checkbox_input")).isSelected();
assertEquals(isSelectedCheck,true);
// TagName
// returns TagName of the element
String tagNameInp = driver.findElement(By.name("email_input")).getTagName();
assertEquals(tagNameInp,"input");
// 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(res.getX(),10);
// 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
Show full example
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;
Show full example
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
Show full example
# 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();
Show full example
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 ins 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())
Get CSS Value
Retrieves the value of specified computed style property of an element in the current browsing context.
// Retrieves the computed style property 'font-size' of field
String cssValue = driver.findElement(By.name("color_input")).getCssValue("font-size");
Show full example
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;
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();
assertEquals(isEmailVisible,true);
// isEnabled
// returns true if element is enabled else returns false
boolean isEnabledButton = driver.findElement(By.name("button_input")).isEnabled();
assertEquals(isEnabledButton,true);
// isSelected
// returns true if element is checked else returns false
boolean isSelectedCheck = driver.findElement(By.name("checkbox_input")).isSelected();
assertEquals(isSelectedCheck,true);
// TagName
// returns TagName of the element
String tagNameInp = driver.findElement(By.name("email_input")).getTagName();
assertEquals(tagNameInp,"input");
// 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(res.getX(),10);
// 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"
)
Show full example
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");
Show full example
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')
Show full example
# 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');
Show full example
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 ins 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")
Text Content
Retrieves the rendered text of the specified element.
// GetText
// Retrieves the text of the element
String text = driver.findElement(By.tagName("h1")).getText();
Show full example
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;
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();
assertEquals(isEmailVisible,true);
// isEnabled
// returns true if element is enabled else returns false
boolean isEnabledButton = driver.findElement(By.name("button_input")).isEnabled();
assertEquals(isEnabledButton,true);
// isSelected
// returns true if element is checked else returns false
boolean isSelectedCheck = driver.findElement(By.name("checkbox_input")).isSelected();
assertEquals(isSelectedCheck,true);
// TagName
// returns TagName of the element
String tagNameInp = driver.findElement(By.name("email_input")).getTagName();
assertEquals(tagNameInp,"input");
// 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(res.getX(),10);
// 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
Show full example
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;
Show full example
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
Show full example
# 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();
Show full example
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 ins 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()
Fetching Attributes or Properties
Fetches the run time value associated with a DOM attribute. It returns the data associated with the DOM attribute or property of the element.
// 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");
Show full example
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;
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();
assertEquals(isEmailVisible,true);
// isEnabled
// returns true if element is enabled else returns false
boolean isEnabledButton = driver.findElement(By.name("button_input")).isEnabled();
assertEquals(isEnabledButton,true);
// isSelected
// returns true if element is checked else returns false
boolean isSelectedCheck = driver.findElement(By.name("checkbox_input")).isSelected();
assertEquals(isSelectedCheck,true);
// TagName
// returns TagName of the element
String tagNameInp = driver.findElement(By.name("email_input")).getTagName();
assertEquals(tagNameInp,"input");
// 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(res.getX(),10);
// 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")
Show full example
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");
Show full example
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')
Show full example
# 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");
Show full example
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 ins 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")