Selenium-locators

提供:Dev Guides
移動先:案内検索

セレン-ロケーター

Selenium WebDriverでの要素の検索は、WebDriverおよびWebElementクラスによって提供されるfindElement()およびfindElements()メソッドの助けを借りて実行されます。

  • findElement()は、指定された検索条件に基づいてWebElementオブジェクトを返すか、検索条件に一致する要素が見つからない場合に例外をスローします。
  • findElements()は、検索条件に一致するWebElementsのリストを返します。 要素が見つからない場合、空のリストを返します。

次の表は、Selenium WebDriverで要素を見つけるためのすべてのJava構文を示しています。

Method Syntax Description
By ID driver.findElement(By.id (<element ID>)) Locates an element using the ID attribute
By name driver.findElement(By.name (<element name>)) Locates an element using the Name attribute
By class name driver.findElement(By.className (<element class>)) Locates an element using the Class attribute
By tag name driver.findElement(By.tagName (<htmltagname>)) Locates an element using the HTML tag
By link text driver.findElement(By.linkText (<linktext>)) Locates a link using link text
By partial link text driver.findElement(By.partialLinkText (<linktext>)) Locates a link using the link’s partial text
By CSS driver.findElement(By.cssSelector (<css selector>)) Locates an element using the CSS selector
By XPath driver.findElement(By.xpath (<xpath>)) Locates an element using XPath query

ロケーターの使用

https://www.calculator.netの助けを借りて、各ロケーターメソッドの実際の使用法を理解しましょう。

IDで

ここでは、IDを使用してオブジェクトにアクセスします。 この場合、それはテキストボックスのIDです。 ID(cdensity)を使用してsendkeysメソッドを使用して、テキストボックスに値を入力します。

Selenium IDE 84

driver.findElement(By.id("cdensity")).sendKeys("10");

名前で

ここでは、名前の助けを借りてオブジェクトにアクセスします。 この場合、それはテキストボックスの名前です。 ID(cdensity)を使用してsendkeysメソッドを使用して、テキストボックスに値を入力します。

Selenium IDE 85

driver.findElement(By.name("cdensity")).sendKeys("10");

クラス名別

ここでは、クラス名を使用してオブジェクトにアクセスします。 この場合、それはWebElementのクラス名です。 値は、gettextメソッドを使用してアクセスできます。

Selenium IDE 86

List<WebElement> byclass = driver.findElements(By.className("smalltext smtb"));

タグ名別

要素のDOMタグ名を使用して、WebDriverで特定の要素を見つけることができます。 この方法を使用すると、テーブルを簡単に処理できます。 次のコードを見てください。

WebElement table = driver.findElement(By.id("calctable"));
List<WebElement> row = table.findElements(By.tagName("tr"));
int rowcount = row.size();

リンクテキスト

このメソッドは、一致する可視テキストを持つリンク要素を見つけるのに役立ちます。

Selenium IDE 87

driver.findElements(By.linkText("Volume")).click();

部分的なリンクテキスト

このメソッドは、部分的に一致する可視テキストを持つリンク要素を見つけるのに役立ちます。

Selenium IDE 87

driver.findElement(By.partialLinkText("Volume")).click();

CSSで

CSSはWebオブジェクトを識別する方法として使用されますが、すべてのブラウザーがCSS識別をサポートしているわけではありません。

WebElement loginButton = driver.findElement(By.cssSelector("input.login"));

XPathによる

XPathはXMLパス言語の略です。 これは、XMLドキュメントからノードを選択するためのクエリ言語です。 XPathはXMLドキュメントのツリー表現に基づいており、さまざまな基準を使用してノードを選択することでツリー内をナビゲートする機能を提供します。

Selenium IDE 88

driver.findElement(By.xpath(".//*[@id = 'content']/table[1]/tbody/tr/td/table/tbody/tr[2]/td[1]/input")).sendkeys("100");