What is XPath
XPath is the abbreviation for XML path, because the HTML document itself is a standard XML page, so we can use the XPath usage to locate page elements.
Disadvantages of XPath positioning
XPath's positioning method, Webdriver will scan all the elements of the entire page to locate the elements we need, this is a very time-consuming operation, if the script is a lot of using XPath to locate the element, the script will be executed a little bit slower
The testxpath.html code is as follows
Absolute path Positioning methodIn the tested Web page, find the button in the first div tag
An XPath expression
/html/body/div/input[@value = "Query"]
Webelement button = driver.findelement (By.xpath ("/html/body/div/input[@value = ' query ']");
Using the browser debugging tool, you can get the XPath statement directlyDisadvantages of absolute paths1. Once the page structure has changed, the path will be invalidated and must be restarted. So it is not recommended to use absolute path notation
The difference between an absolute path and a relative pathThe absolute path begins with "/" and the XPath begins parsing from the root node of the document
The relative path begins with "//" and allows the XPath to begin parsing from any element node of the document
Relative path Positioning methodIn the tested Web page, find the button in the first div tag
An XPath expression
input[@value = "Query"]
Webelement button = driver.findelement (By.xpath ("//input[@value = ' query ']");
Using index numbers to locateIn the tested Web page, find the query button in the second div tag
INPUT[2]
Webelement button = driver.findelement (By.xpath ("//input[2]"));
Using Page properties to navigatePosition the first picture element in the page being tested
img[@alt = ' div1-img1 ')
Webelement button = driver.findelement (By.xpath ("//img[@alt = ' div1-img1 ']");
Fuzzy positioning Starts-with KeywordsFind the image alt attribute start position contains the ' div1 ' keyword element
Img[starts-with (@alt, ' div ')]
Fuzzy positioning contains keywordsFind picture alt attribute contains the ' G1 ' keyword element
Img[contains (@alt, ' G1 ')]
Text () function to locate all text "Baidu search" elementsDriver.findelement (By.xpath ("//*[text () = ' Baidu search ']");
Find all hyperlinks with text "search"Driver.findelement (By.xpath ("//a[contains (Text (), ' Search ')]);
Java Selenium (vi) XPath positioning