官术网_书友最值得收藏!

The By.xpath() method

WebDriver uses XPath to identify a WebElement on the web page. Before we see how it does that, let's quickly look at the syntax for XPath. XPath is a short name for the XML path, the query language used for searching XML documents. The HTML for our web page is also one form of the XML document. So, in order to identify an element on an HTML page, we need to use a specific XPath syntax:

  • The root element is identified as //.
  • To identify all the div elements, the syntax will be //div.
  • To identify the link tags that are within the div element, the syntax will be //div/a.
  • To identify all the elements with a tag, we use *. The syntax will be //div/*.
  • To identify all the div elements that are at three levels down from the root, we can use //*/*/div.
  • To identify specific elements, we use attribute values of those elements, such as //*/div/a[@id='attrValue'], which will return the anchor element. This element is at the third level from the root within a div element and has an id value of attrValue.

So, we need to pass the XPath expression to the By.xpath locating mechanism to make it identify our target element. 

Now, let's see the code example and how WebDriver uses this XPath to identify the element:

@Test
public void byXPathLocatorExample() {
WebElement searchBox =
driver.findElement(By.xpath("http://*[@id='search']"));
searchBox.sendKeys("Bags");
searchBox.submit();
assertThat(driver.getTitle())
.isEqualTo("Search results for: 'Bags'");
}

In the preceding code, we are using the By.xpath locating mechanism and passing the XPath of the WebElement to it.

One disadvantage of using XPath is that it is costly in terms of time. For every element to be identified, WebDriver actually scans through the entire page, which is very time consuming, and too much usage of XPath in your test script will actually make it too slow to execute.

主站蜘蛛池模板: 东乌| 当涂县| 永修县| 张家口市| 瓮安县| 汽车| 渝北区| 印江| 尉犁县| 河津市| 牙克石市| 周宁县| 桐柏县| 商城县| 沈丘县| 潍坊市| 宜昌市| 临汾市| 清苑县| 措美县| 泊头市| 简阳市| 交口县| 涪陵区| 奎屯市| 咸宁市| 泾阳县| 宁德市| 雷波县| 建德市| 措美县| 日喀则市| 无为县| 咸宁市| 应用必备| 石狮市| 吉隆县| 玛沁县| 河西区| 伊金霍洛旗| 荣成市|