- Selenium WebDriver 3 Practical Guide
- Unmesh Gundecha Satya Avasarala
- 315字
- 2021-08-13 16:08:08
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.
- Truffle Quick Start Guide
- SEO 20日
- WordPress 5 Complete
- 信息通信網(wǎng)絡(luò)建設(shè)安全管理概要2
- 網(wǎng)絡(luò)基礎(chǔ)與網(wǎng)絡(luò)管理項目化教程
- 物聯(lián)網(wǎng)長距離無線通信技術(shù)應(yīng)用與開發(fā)
- Working with Legacy Systems
- 基于性能的保障理論與方法
- Professional Scala
- 世界互聯(lián)網(wǎng)發(fā)展報告2021
- 物聯(lián)網(wǎng)技術(shù)與實踐
- 互聯(lián)網(wǎng)安全的40個智慧洞見(2018)
- CDN技術(shù)詳解
- 企業(yè)網(wǎng)絡(luò)組建與維護項目式教程
- LiveCode Mobile Development Beginner's Guide