- 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.
- Application Development with Qt Creator(Second Edition)
- SEO 20日
- 網絡互聯技術(實踐篇)
- 面向云平臺的物聯網多源異構信息融合方法
- Mastering TypeScript 3
- Building RESTful Web services with Go
- 網管工具使用與技巧大全
- 網絡AI+:2030后的未來網絡
- Getting Started with nopCommerce
- AIoT應用開發與實踐
- 轉化:提升網站流量和轉化率的技巧
- 現代通信系統(第5版)
- Selenium WebDriver 3 Practical Guide
- 華為HCIA-Datacom認證指南
- 現場綜合化網絡運營與維護:運營商數字化轉型技術與實踐