ほとんどの人のSeleniumコードの大部分は、Web要素の操作に関連しています。
これは、このセクションの複数ページの印刷可能なビューです。 印刷するには、ここをクリックしてください.
Web要素
- 1: 要素を探す
- 2: Interacting with web elements
- 3: Web要素の検索
- 4: Web要素に関する情報
- 5: 選択要素の操作
1 - 要素を探す
ロケーターは、ページ上の要素を識別する方法です。 これは、検索要素 メソッドに渡される引数です。
検出方法とは別にロケーターを宣言するタイミングと理由など、 ロケーターに関するヒントについては、 推奨されるテストプラクティス を確認してください。
要素選択の方法
WebDriverには標準のロケータが8種類あります。
ロケータ | 詳細 |
---|---|
class name | class名に値を含む要素を探す (複合クラス名は使えない) |
css selector | CSSセレクタが一致する要素を探す |
id | id属性が一致する要素を探す |
name | name属性が一致する要素を探す |
link text | a要素のテキストが一致する要素を探す |
partial link text | a要素のテキストが部分一致する要素を探す |
tag name | タグ名が一致する要素を探す |
xpath | XPathと一致する要素を探す |
Coding Help
of selecting elements using each locator strategy
Check our contribution guidelines and code example formats if you’d like to help.
相対ロケーター
Selenium 4 introduces Relative Locators (previously called as Friendly Locators). These locators are helpful when it is not easy to construct a locator for the desired element, but easy to describe spatially where the element is in relation to an element that does have an easily constructed locator.
How it works
Selenium uses the JavaScript function
getBoundingClientRect()
to determine the size and position of elements on the page, and can use this information to locate neighboring elements.
find the relative elements.
Relative locator methods can take as the argument for the point of origin, either a previously located element reference, or another locator. In these examples we’ll be using locators only, but you could swap the locator in the final method with an element object and it will work the same.
Let us consider the below example for understanding the relative locators.

Available relative locators
Above
If the email text field element is not easily identifiable for some reason, but the password text field element is, we can locate the text field element using the fact that it is an “input” element “above” the password element.
By emailLocator = RelativeLocator.with(By.tagName("input")).above(By.id("password"));
email_locator = locate_with(By.TAG_NAME, "input").above({By.ID: "password"})
var emailLocator = RelativeBy.WithLocator(By.TagName("input")).Above(By.Id("password"));
email_locator = {relative: {tag_name: 'input', above: {id: 'password'}}}
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"));
password_locator = {relative: {tag_name: 'input', below: {id: 'email'}}}
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"));
cancel_locator = {relative: {tag_name: 'button', left: {id: 'submit'}}}
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"));
submit_locator = {relative: {tag_name: 'button', right: {id: 'cancel'}}}
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"));
email_locator = {relative: {tag_name: 'input', near: {id: 'lbl-email'}}}
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"));
submit_locator = {relative: {tag_name: 'button', below: {id: 'email'}, right: {id: 'cancel'}}}
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"))
2 - 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.
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 acontent-editable
attribute. If it is not editable,
an invalid element state error is returned.
Here is the list of possible keystrokes that WebDriver Supports.
import org.openqa.selenium.By;
import org.openqa.selenium.Keys;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
public class HelloSelenium {
public static void main(String[] args) {
WebDriver driver = new FirefoxDriver();
try {
// Navigate to Url
driver.get("https://google.com");
// Enter text "q" and perform keyboard action "Enter"
driver.findElement(By.name("q")).sendKeys("q" + Keys.ENTER);
} finally {
driver.quit();
}
}
}
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.common.keys import Keys
driver = webdriver.Firefox()
# Navigate to url
driver.get("http://www.google.com")
# Enter "webdriver" text and perform "ENTER" keyboard action
driver.find_element(By.NAME, "q").send_keys("webdriver" + Keys.ENTER)
using (var driver = new FirefoxDriver())
{
// Navigate to Url
driver.Navigate().GoToUrl("https://google.com");
// Enter "webdriver" text and perform "ENTER" keyboard action
driver.FindElement(By.Name("q")).SendKeys("webdriver" + Keys.Enter);
}
require 'selenium-webdriver'
driver = Selenium::WebDriver.for :firefox
begin
# Navigate to URL
driver.get 'https://google.com'
# Enter "webdriver" text and perform "ENTER" keyboard action
driver.find_element(name: 'q').send_keys 'webdriver', :return
ensure
driver.quit
end
const {Builder, By, Key} = require('selenium-webdriver');
(async function example() {
let driver = await new Builder().forBrowser('firefox').build();
try {
// Navigate to Url
await driver.get('https://www.google.com');
// Enter text "webdriver" and perform keyboard action "Enter"
await driver.findElement(By.name('q')).sendKeys('webdriver', Key.ENTER);
}
finally {
await driver.quit();
}
})();
import org.openqa.selenium.By
import org.openqa.selenium.Keys
import org.openqa.selenium.firefox.FirefoxDriver
fun main() {
val driver = FirefoxDriver()
try {
// Navigate to Url
driver.get("https://google.com")
// Enter text "q" and perform keyboard action "Enter"
driver.findElement(By.name("q")).sendKeys("q" + Keys.ENTER)
} finally {
driver.quit()
}
}
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.
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
public class clear {
public static void main(String[] args) {
WebDriver driver = new ChromeDriver();
try {
// Navigate to Url
driver.get("https://www.google.com");
// Store 'SearchInput' element
WebElement searchInput = driver.findElement(By.name("q"));
searchInput.sendKeys("selenium");
// Clears the entered text
searchInput.clear();
} finally {
driver.quit();
}
}
}
from selenium import webdriver
from selenium.webdriver.common.by import By
driver = webdriver.Chrome()
# Navigate to url
driver.get("http://www.google.com")
# Store 'SearchInput' element
SearchInput = driver.find_element(By.NAME, "q")
SearchInput.send_keys("selenium")
# Clears the entered text
SearchInput.clear()
using OpenQA.Selenium;
using OpenQA.Selenium.Chrome;
using System;
namespace SnipetProjectDelete
{
class Program
{
static void Main(string[] args)
{
IWebDriver driver = new ChromeDriver();
try
{
// Navigate to Url
driver.Navigate().GoToUrl(@"https://www.google.com");
// Store 'SearchInput' element
IWebElement searchInput = driver.FindElement(By.Name("q"));
searchInput.SendKeys("selenium");
// Clears the entered text
searchInput.Clear();
}
finally
{
driver.Quit();
}
}
}
}
require 'selenium-webdriver'
driver = Selenium::WebDriver.for :chrome
begin
# Navigate to URL
driver.get 'https://google.com'
# store 'search_input' element
search_input = driver.find_element(name: 'q')
search_input.send_keys('selenium')
# Clears the entered text
search_input.clear
ensure
driver.quit
end
const {Builder, By} = require('selenium-webdriver');
(async function example() {
let driver = await new Builder().forBrowser('chrome').build();
try {
// Navigate to Url
await driver.get('https://www.google.com');
// Store 'SearchInput' element
let searchInput = driver.findElement(By.name('q'));
await searchInput.sendKeys("selenium");
// Clears the entered text
await searchInput.clear();
}
finally {
await driver.quit();
}
})();
import org.openqa.selenium.By
import org.openqa.selenium.chrome.ChromeDriver
fun main() {
val driver = ChromeDriver()
try {
// Navigate to Url
driver.get("https://www.google.com")
// Store 'searchInput' element
val searchInput = driver.findElement(By.name("q"))
searchInput.sendKeys("selenium")
// Clears the entered text
searchInput.clear()
} finally {
driver.quit()
}
}
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.
3 - Web要素の検索
Seleniumを使用する最も基本的な側面の1つは、操作する要素の参照を取得することです。 Seleniumは、要素を一意に識別するための多数の組み込みロケーター戦略を提供します。 非常に高度なシナリオでロケーターを使用する方法はたくさんあります。 このドキュメントの目的のために、このHTMLスニペットについて考えてみましょう。
<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>
最初に一致する要素
多くのロケーターは、ページ上の複数の要素と一致します。 単数の find elementメソッドは、指定されたコンテキスト内で最初に見つかった要素への参照を返します。
DOM全体の評価
ドライバーインスタンスで要素の検索メソッドが呼び出されると、提供されたロケーターと一致するDOMの最初の要素への参照が返されます。 この値は保存して、将来の要素アクションに使用できます。 上記のHTMLの例では、クラス名が “tomatoes” の要素が2つあるため、このメソッドは “vegetables” リストの要素を返します。
WebElement vegetable = driver.findElement(By.className("tomatoes"));
vegetable = driver.find_element(By.CLASS_NAME, "tomatoes")
var vegetable = driver.FindElement(By.ClassName("tomatoes"));
vegetable = driver.find_element(class: 'tomatoes')
const vegetable = driver.findElement(By.className('tomatoes'));
val vegetable: WebElement = driver.findElement(By.className("tomatoes"))
DOMのサブセットの評価
DOM全体で一意のロケーターを見つけるのではなく、検索を別の検索された要素のスコープに絞り込むと便利なことがよくあります。 上記の例では、クラス名が “トマト” の2つの要素があり、2番目の要素の参照を取得するのは少し困難です。
1つの解決策は、目的の要素の祖先であり、不要な要素の祖先ではない一意の属性を持つ要素を見つけて、そのオブジェクトでfind要素を呼び出すことです。
WebElement fruits = driver.findElement(By.id("fruits"));
WebElement fruit = fruits.findElement(By.id("tomatoes"));
fruits = driver.find_element(By.ID, "fruits")
fruit = fruits.find_elements_by_id("tomatoes")
IWebElement fruits = driver.FindElement(By.Id("fruits"));
IWebElement fruit = fruits.FindElement(By.Id("tomatoes"));
fruits = driver.find_element(id: 'fruits')
fruit = fruits.find_element(id: 'tomatoes')
const fruits = driver.findElement(By.id('fruits'));
const fruit = fruits.findElement(By.id('tomatoes'));
val fruits = driver.findElement(By.id("fruits"))
val fruit = fruits.findElement(By.id("tomatoes"))
Java and C#WebDriver
、 WebElement
、および ShadowRoot
クラスはすべて、 ロールベースのインターフェイス と見なされる SearchContext
インターフェイスを実装します。
ロールベースのインターフェイスを使用すると、特定のドライバーの実装が特定の機能をサポートしているかどうかを判断できます。
これらのインターフェースは明確に定義されており、責任の役割を1つだけ持つように努めています。
最適化されたロケーター
ネストされたルックアップは、ブラウザに2つの別々のコマンドを発行する必要があるため、最も効果的なロケーション戦略ではない可能性があります。
パフォーマンスをわずかに向上させるために、CSSまたはXPathのいずれかを使用して、単一のコマンドでこの要素を見つけることができます。 推奨されるテストプラクティスの章で、ロケーター戦略の提案を参照してください。
この例では、CSSセレクターを使用します。
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"));
fruit = driver.find_element(css: '#fruits .tomatoes')
const fruit = driver.findElement(By.css('#fruits .tomatoes'));
val fruit = driver.findElement(By.cssSelector("#fruits .tomatoes"))
一致するすべての要素
最初の要素だけでなく、ロケーターに一致するすべての要素への参照を取得する必要があるユースケースがいくつかあります。 複数の要素の検索メソッドは、要素参照のコレクションを返します。 一致するものがない場合は、空のリストが返されます。 この場合、すべてのfruitsとvegetableのリストアイテムへの参照がコレクションに返されます。
List<WebElement> plants = driver.findElements(By.tagName("li"));
plants = driver.find_elements(By.TAG_NAME, "li")
IReadOnlyList<IWebElement> plants = driver.FindElements(By.TagName("li"));
plants = driver.find_elements(tag_name: 'li')
const plants = driver.findElements(By.tagName('li'));
val plants: List<WebElement> = driver.findElements(By.tagName("li"))
要素の取得
多くの場合、要素のコレクションを取得しますが、特定の要素を操作したいので、コレクションを繰り返し処理して、 必要な要素を特定する必要があります。
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();
}
}
}
}
require 'selenium-webdriver'
driver = Selenium::WebDriver.for :firefox
begin
# Navigate to URL
driver.get 'https://www.example.com'
# Get all the elements available with tag name 'p'
elements = driver.find_elements(:tag_name,'p')
elements.each { |e|
puts e.text
}
ensure
driver.quit
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()
}
}
要素から要素を検索
これは、親要素のコンテキスト内で一致する子のWebElementのリストを見つけるために利用されます。 これを実現するために、親WebElementは’findElements’と連鎖して子要素にアクセスします。
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 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)
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();
}
}
}
}
require 'selenium-webdriver'
driver = Selenium::WebDriver.for :chrome
begin
# Navigate to URL
driver.get 'https://www.example.com'
# Get element with tag name 'div'
element = driver.find_element(:tag_name,'div')
# Get all the elements available with tag name 'p'
elements = element.find_elements(:tag_name,'p')
elements.each { |e|
puts e.text
}
ensure
driver.quit
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()
}
}
アクティブな要素を取得する
これは、現在のブラウジングコンテキストでフォーカスを持っているDOM要素を追跡(または)検索するために使用されます。
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();
}
}
}
}
require 'selenium-webdriver'
driver = Selenium::WebDriver.for :chrome
begin
driver.get 'https://www.google.com'
driver.find_element(css: '[name="q"]').send_keys('webElement')
# Get attribute of current active element
attr = driver.switch_to.active_element.attribute('title')
puts attr
ensure
driver.quit
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 - Web要素に関する情報
特定の要素についてクエリできる詳細情報がいくつかあります。
表示されているかどうか
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.
// Navigate to the url
driver.get('https://www.google.com');
// Get boolean value for is element display
boolean isButtonVisible = driver.findElement(By.css("[name='login']")).isDisplayed();
# Navigate to the url
driver.get("https://www.google.com")
# Get boolean value for is element display
is_button_visible = driver.find_element(By.CSS_SELECTOR, "[name='login']").is_displayed()
// Help us with a PR for code sample
# Help us with a PR for code sample
// Navigate to url
await driver.get('https://www.google.com');
// Resolves Promise and returns boolean value
let result = await driver.findElement(By.css("[name='btnK']")).isDisplayed();
// Help us with a PR for code sample
Coding Help
for element displayedness
Check our contribution guidelines and code example formats if you’d like to help.
要素が有効か
このメソッドは、接続された要素がWebページで有効または無効になっているかどうかを確認するために使います。 ブール値を返し、現在のブラウジングコンテキストで接続されている要素が 有効(enabled) になっている場合は True 、そうでない場合は false を返します。
//navigates to url
driver.get("https://www.google.com/");
//returns true if element is enabled else returns false
boolean value = driver.findElement(By.name("btnK")).isEnabled();
# Navigate to url
driver.get("http://www.google.com")
# Returns true if element is enabled else returns false
value = driver.find_element(By.NAME, 'btnK').is_enabled()
// Navigate to Url
driver.Navigate().GoToUrl("https://google.com");
// Store the WebElement
IWebElement element = driver.FindElement(By.Name("btnK"));
// Prints true if element is enabled else returns false
System.Console.WriteLine(element.Enabled);
# Navigate to url
driver.get 'http://www.google.com/'
# Returns true if element is enabled else returns false
ele = driver.find_element(name: 'btnK').enabled?
// Navigate to url
await driver.get('https://www.google.com');
// Resolves Promise and returns boolean value
let element = await driver.findElement(By.name("btnK")).isEnabled();
//navigates to url
driver.get("https://www.google.com/")
//returns true if element is enabled else returns false
val attr = driver.findElement(By.name("btnK")).isEnabled()
要素が選択されているかどうか
このメソッドは、参照された要素が選択されているかどうかを判断します。 このメソッドは、チェックボックス、ラジオボタン、入力要素、およびオプション要素で広く使われています。
ブール値を返し、現在のブラウジングコンテキストで参照された要素が 選択されている 場合は True 、そうでない場合は false を返します。
//navigates to url
driver.get("https://the-internet.herokuapp.com/checkboxes");
//returns true if element is checked else returns false
boolean value = driver.findElement(By.cssSelector("input[type='checkbox']:first-of-type")).isSelected();
# Navigate to url
driver.get("https://the-internet.herokuapp.com/checkboxes")
# Returns true if element is checked else returns false
value = driver.find_element(By.CSS_SELECTOR, "input[type='checkbox']:first-of-type").is_selected()
// Navigate to Url
driver.Navigate().GoToUrl("https://the-internet.herokuapp.com/checkboxes");
// Returns true if element ins checked else returns false
bool value = driver.FindElement(By.CssSelector("input[type='checkbox']:last-of-type")).Selected;
# Navigate to url
driver.get 'https://the-internet.herokuapp.com/checkboxes'
# Returns true if element is checked else returns false
ele = driver.find_element(css: "input[type='checkbox']:last-of-type").selected?
// Navigate to url
await driver.get('https://the-internet.herokuapp.com/checkboxes');
// Returns true if element ins checked else returns false
let res = await driver.findElement(By.css("input[type='checkbox']:last-of-type")).isSelected();
//navigates to url
driver.get("https://the-internet.herokuapp.com/checkboxes")
//returns true if element is checked else returns false
val attr = driver.findElement(By.cssSelector("input[type='checkbox']:first-of-type")).isSelected()
要素のタグ名を取得
これは、現在のブラウジングコンテキストにフォーカスがある参照された要素の TagName を取得するために使います。
//navigates to url
driver.get("https://www.example.com");
//returns TagName of the element
String value = driver.findElement(By.cssSelector("h1")).getTagName();
# Navigate to url
driver.get("https://www.example.com")
# Returns TagName of the element
attr = driver.find_element(By.CSS_SELECTOR, "h1").tag_name
// Navigate to Url
driver.Navigate().GoToUrl("https://www.example.com");
// Returns TagName of the element
string attr = driver.FindElement(By.CssSelector("h1")).TagName;
# Navigate to url
driver.get 'https://www.example.com'
# Returns TagName of the element
attr = driver.find_element(css: "h1").tag_name
// Navigate to URL
await driver.get('https://www.example.com');
// Returns TagName of the element
let value = await driver.findElement(By.css('h1')).getTagName();
//navigates to url
driver.get("https://www.example.com")
//returns TagName of the element
val attr = driver.findElement(By.cssSelector("h1")).getTagName()
要素矩形を取得
参照される要素の寸法と座標を取得するために使います。
取得データのbodyには、次の詳細が含まれます。
- 要素の左上隅からのx軸の位置
- 要素の左上隅からのy軸の位置
- 要素の高さ
- 要素の幅
// Navigate to url
driver.get("https://www.example.com");
// Returns height, width, x and y coordinates referenced element
Rectangle res = driver.findElement(By.cssSelector("h1")).getRect();
// Rectangle class provides getX,getY, getWidth, getHeight methods
System.out.println(res.getX());
# Navigate to url
driver.get("https://www.example.com")
# Returns height, width, x and y coordinates referenced element
res = driver.find_element(By.CSS_SELECTOR, "h1").rect
// Navigate to Url
driver.Navigate().GoToUrl("https://example.com");
var res = driver.FindElement(By.CssSelector("h1"));
// Return x and y coordinates referenced element
System.Console.WriteLine(res.Location);
// Returns height, width
System.Console.WriteLine(res.Size);
# Navigate to url
driver.get 'https://www.example.com'
# Returns height, width, x and y coordinates referenced element
res = driver.find_element(css: "h1").rect
// Navigate to url
await driver.get('https://www.example.com');
// Returns height, width, x and y coordinates referenced element
let element = await driver.findElement(By.css("h1")).getRect();
// Navigate to url
driver.get("https://www.example.com")
// Returns height, width, x and y coordinates referenced element
val res = driver.findElement(By.cssSelector("h1")).rect
// Rectangle class provides getX,getY, getWidth, getHeight methods
println(res.getX())
要素のCSSの値を取得
現在のブラウジングコンテキスト内の要素の指定された計算したスタイル属性の値を取得します。
// Navigate to Url
driver.get("https://www.example.com");
// Retrieves the computed style property 'color' of linktext
String cssValue = driver.findElement(By.linkText("More information...")).getCssValue("color");
# Navigate to Url
driver.get('https://www.example.com')
# Retrieves the computed style property 'color' of linktext
cssValue = driver.findElement(By.LINK_TEXT, "More information...").value_of_css_property('color')
// Navigate to Url
driver.Navigate().GoToUrl("https://www.example.com");
// Retrieves the computed style property 'color' of linktext
String cssValue = driver.FindElement(By.LinkText("More information...")).GetCssValue("color");
# Navigate to Url
driver.get 'https://www.example.com'
# Retrieves the computed style property 'color' of linktext
cssValue = driver.find_element(:link_text, 'More information...').css_value('color')
// Navigate to Url
await driver.get('https://www.example.com');
// Retrieves the computed style property 'color' of linktext
let cssValue = await driver.findElement(By.linkText("More information...")).getCssValue('color');
// Navigate to Url
driver.get("https://www.example.com")
// Retrieves the computed style property 'color' of linktext
val cssValue = driver.findElement(By.linkText("More information...")).getCssValue("color")
要素テキストを取得
指定された要素のレンダリングされたテキストを取得します。
// Navigate to url
driver.get("https://example.com");
// Retrieves the text of the element
String text = driver.findElement(By.cssSelector("h1")).getText();
# Navigate to url
driver.get("https://www.example.com")
# Retrieves the text of the element
text = driver.find_element(By.CSS_SELECTOR, "h1").text
// Navigate to url
driver.Url="https://example.com";
// Retrieves the text of the element
String text = driver.FindElement(By.CssSelector("h1")).Text;
# Navigate to url
driver.get 'https://www.example.com'
# Retrieves the text of the element
text = driver.find_element(:css, 'h1').text
// Navigate to URL
await driver.get('http://www.example.com');
// retrieves the text of the element
let text = await driver.findElement(By.css('h1')).getText();
// Navigate to URL
driver.get("https://www.example.com")
// retrieves the text of the element
val text = driver.findElement(By.cssSelector("h1")).getText()
属性とプロパティ
属性
DOMの属性
DOMのプロパティ
5 - 選択要素の操作
一部の要素では、自動化するためにかなりのボイラープレートコードが必要になる場合があります。
これを減らしてテストをきれいにするために、Seleniumサポートパッケージに Select
クラスがあります。
それを使用するには、次のimportステートメントが必要です。
import org.openqa.selenium.support.ui.Select;
from selenium.webdriver.support.select import Select
using OpenQA.Selenium.Support.UI
include Selenium::WebDriver::Support
// This feature is not implemented - Help us by sending a pr to implement this feature
import org.openqa.selenium.support.ui.Select
そして、 <select>
要素を参照するWebElementを使用してSelectオブジェクトを作成できます。
WebElement selectElement = driver.findElement(By.id("selectElementID"));
Select selectObject = new Select(selectElement);
select_element = driver.find_element(By.ID,'selectElementID')
select_object = Select(select_element)
IWebElement selectElement = driver.FindElement(By.Id("selectElementID"));
var selectObject = new SelectElement(selectElement);
select_element = driver.find_element(id: 'selectElementID')
select_object = Select(select_element)
// This feature is not implemented - Help us by sending a pr to implement this feature
val selectElement = driver.findElement(By.id("selectElementID"))
val selectObject = new Select(selectElement)
Selectオブジェクトは、 <select>
要素とやり取りできる一連のコマンドを提供します。
まず、 <select>
要素からオプションを選択するさまざまな方法があります。
<select>
<option value=value1>Bread</option>
<option value=value2 selected>Milk</option>
<option value=value3>Cheese</option>
</select>
上記の要素から最初のオプションを選択するには、3つの方法があります。
// Select an <option> based upon the <select> element's internal index
selectObject.selectByIndex(1);
// Select an <option> based upon its value attribute
selectObject.selectByValue("value1");
// Select an <option> based upon its text
selectObject.selectByVisibleText("Bread");
# Select an <option> based upon the <select> element's internal index
select_object.select_by_index(1)
# Select an <option> based upon its value attribute
select_object.select_by_value('value1')
# Select an <option> based upon its text
select_object.select_by_visible_text('Bread')
// Select an <option> based upon the <select> element's internal index
selectObject.SelectByIndex(1);
// Select an <option> based upon its value attribute
selectObject.SelectByValue("value1");
// Select an <option> based upon its text
selectObject.SelectByText("Bread");
# Select an <option> based upon the <select> element's internal index
select_object.select_by(:index, 1)
# Select an <option> based upon its value attribute
select_object.select_by(:value, 'value1')
# Select an <option> based upon its text
select_object.select_by(:text, 'Bread')
// This feature is not implemented - Help us by sending a pr to implement this feature
// Select an <option> based upon the <select> element's internal index
selectObject.selectByIndex(1)
// Select an <option> based upon its value attribute
selectObject.selectByValue("value1")
// Select an <option> based upon its text
selectObject.selectByVisibleText("Bread")
以下を使用して、選択されているオプションを確認できます。
// Return a List<WebElement> of options that have been selected
List<WebElement> allSelectedOptions = selectObject.getAllSelectedOptions();
// Return a WebElement referencing the first selection option found by walking down the DOM
WebElement firstSelectedOption = selectObject.getFirstSelectedOption();
# Return a list[WebElement] of options that have been selected
all_selected_options = select_object.all_selected_options
# Return a WebElement referencing the first selection option found by walking down the DOM
first_selected_option = select_object.first_selected_option
// Return a List<WebElement> of options that have been selected
var allSelectedOptions = selectObject.AllSelectedOptions;
// Return a WebElement referencing the first selection option found by walking down the DOM
var firstSelectedOption = selectObject.AllSelectedOptions.FirstOrDefault();
# Return an Array[Element] of options that have been selected
all_selected_options = select_object.selected_options
# Return a WebElement referencing the first selection option found by walking down the DOM
first_selected_option = select_object.first_selected_option
// This feature is not implemented - Help us by sending a pr to implement this feature
// Return a List<WebElement> of options that have been selected
val allSelectedOptions = selectObject.allSelectedOptions
// Return a WebElement referencing the first selection option found by walking down the DOM
val firstSelectedOption = selectObject.firstSelectedOption
または、 <select>
要素に含まれる <option>
要素に興味があるかもしれません。
// Return a List<WebElement> of options that the <select> element contains
List<WebElement> allAvailableOptions = selectObject.getOptions();
# Return a list[WebElement] of options that the <select> element contains
all_available_options = select_object.options
// Return a IList<IWebElement> of options that the <select> element contains
IList<IWebElement> allAvailableOptions = selectObject.Options;
# Return an Array[Element] of options that the <select> element contains
all_available_options = select_object.options
// This feature is not implemented - Help us by sending a pr to implement this feature
// Return a List<WebElement> of options that the <select> element contains
val allAvailableOptions = selectObject.options
要素の選択を解除する場合は、4つの選択肢があります。
// Deselect an <option> based upon the <select> element's internal index
selectObject.deselectByIndex(1);
// Deselect an <option> based upon its value attribute
selectObject.deselectByValue("value1");
// Deselect an <option> based upon its text
selectObject.deselectByVisibleText("Bread");
// Deselect all selected <option> elements
selectObject.deselectAll();
# Deselect an <option> based upon the <select> element's internal index
select_object.deselect_by_index(1)
# Deselect an <option> based upon its value attribute
select_object.deselect_by_value('value1')
# Deselect an <option> based upon its text
select_object.deselect_by_visible_text('Bread')
# Deselect all selected <option> elements
select_object.deselect_all()
// Deselect an <option> based upon the <select> element's internal index
selectObject.DeselectByIndex(1);
// Deselect an <option> based upon its value attribute
selectObject.DeselectByValue("value1");
// Deselect an <option> based upon its text
selectObject.DeselectByText("Bread");
// Deselect all selected <option> elements
selectObject.DeselectAll();
# Deselect an <option> based upon the <select> element's internal index
select_object.deselect_by(:index, 1)
# Deselect an <option> based upon its value attribute
select_object.deselect_by(:value, 'value1')
# Deselect an <option> based upon its text
select_object.deselect_by(:text, 'Bread')
# Deselect all selected <option> elements
select_object.deselect_all
// This feature is not implemented - Help us by sending a pr to implement this feature
// Deselect an <option> based upon the <select> element's internal index
selectObject.deselectByIndex(1)
// Deselect an <option> based upon its value attribute
selectObject.deselectByValue("value1")
// Deselect an <option> based upon its text
selectObject.deselectByVisibleText("Bread")
// Deselect all selected <option> elements
selectObject.deselectAll()
最後に、一部の <select>
要素を使用すると、複数のオプションを選択できます。
<select>
要素がこれらの1つであるかどうかを調べるには、下記のように記述します。
Boolean doesThisAllowMultipleSelections = selectObject.isMultiple();
does_this_allow_multiple_selections = select_object.is_multiple
bool doesThisAllowMultipleSelections = selectObject.IsMultiple;
does_this_allow_multiple_selections = select_object.multiple?
// This feature is not implemented - Help us by sending a pr to implement this feature
val doesThisAllowMultipleSelections = selectObject.isMultiple