The two methods described in this chapter are positioning operations on text links on Web pages. According to the name, we can see that the two are actually very similar, then they are different.
by LinkText () method, is a hyperlink to a Web page, and we need to enter all the text for the hyperlink for the keyword.
by Partiallinktext () method, see part of the word we can know, when the text hyperlink is too long, we do not want to enter so many words, we can call this method, the main input belongs to this hyperlink text portion of the. Of course, in order to prevent the text from appearing too much position, the proposed character should be unique.
Here then use Baidu Homepage For example, example for the red box content, the code shows as follows:
Importorg.openqa.selenium.By;ImportOrg.openqa.selenium.WebDriver;ImportOrg.openqa.selenium.chrome.ChromeDriver; Public classFindelement_linktext { Public Static voidMain (string[] args)throwsException {system.setproperty ("Webdriver.chrome.driver", ". \\Tools\\chromedriver.exe"); Webdriver Driver=NewChromedriver (); Driver.manage (). window (). Maximize (); Driver.get ("Https://www.baidu.com"); //by LinkText Find elementsDriver.findelement (By.linktext ("News")) . Click (); Thread.Sleep (1000);
Back to Baidu homepage
Driver.navigate (). back ();
Thread.Sleep (1000);
//by Partiallinktext Find elementsDriver.findelement (By.partiallinktext ("Set as Home") . Click (); }}
The Thread.Sleep () that appears in the code is the meaning of the pause, and the number in parentheses is Ms. This code is added to ensure the execution of the entire program. Because in the actual operation to do, often appear code error, said to locate the element. Later, after a verification, found that not the element positioning is wrong, but because the page jumps, it may be slow loading speed, the code execution speed, resulting in the element location failure. Therefore, in the case of page jumps or transitions, it is recommended to add a thread.sleep () operation under the line code, so that the code waits for the page to be loaded and then executes, which avoids the error of locating the element that is caused by the slow loading of the page.
Java + Selenium element positioning (2) by Linktext/partiallinktext