This article on the XPath method is the same as the previous CSS method, before using, you need to master some of the XPath knowledge. Of course, there are various tools on the web that can help us get to the XPath of the element, but it doesn't mean that we don't have to know about XPath, after all, the Reliance tool never relies on its own. But I will also introduce the XPath of the element if it is simple and fast.
I have tried to use some of the articles described in the Quick Get XPath tool, but perhaps because these tools are dependent on the browser extension tool, newer and faster, so the article introduced the tool I did not successfully find. I am here to introduce the method that does not require the use of additional tools. In the previous element positioning (1), I have described the use of Browser developer tools to view the source code of the Web page, and also to get some of the elements we want to tag. This chapter is about XPath acquisition and we are also browser-based developer tools. To eradicate the previous steps, we click on the line of code that knows the element we want to get. At this point, we move the mouse over the line code, right-click and select Copy---copy Xpath. This allows us to get an XPath expression for that element. We can see the XPath expression only by selecting paste in any of the input boxes.
For example, our Baidu homepage example. Or the input box of the home page, after this wave operation, we can get the XPath expression to the input box://*[@id = "kw"]. So we can use the By.xpath interface method directly: Driver.findelement (By.xpath (".//*[@id = ' kw ')"). SendKeys ("Automation"). The complete code is shown below
ImportJava.util.concurrent.TimeUnit;Importorg.openqa.selenium.By;ImportOrg.openqa.selenium.WebDriver;ImportOrg.openqa.selenium.chrome.ChromeDriver; Public classFirstscript { Public Static voidMain (string[] args) {System.setproperty ("Webdriver.chrome.driver", ". \\Tools\\chromedriver.exe"); Webdriver Driver=NewChromedriver (); Driver.manage (). window (). Maximize (); Driver.manage (). Timeouts (). Implicitlywait (8, Timeunit.seconds); Driver.get ("Https://www.baidu.com"); Driver.findelement (By.xpath (".//*[@id = ' kw ')"). SendKeys ("Automation"); Driver.findelement (By.xpath (".//*[@id = ' su ']") . Click (); //Close and exit the browserDriver.quit (); } }
Of course, the machine gets the XPath is very rigid, and we in the actual use, because different people's writing habits are different, in fact, the rigid machine is very prone to problems. So it's better for us to identify ourselves on our own.
Java + Selenium element positioning (5) by Xpath