The By.linkText() method
As the name suggests, the By.linkText locating mechanism can only be used to identify the HTML links. Before we start discussing how WebDriver can be commanded to identify a link element using link text, let's see what an HTML link element looks like. The HTML link elements are represented on a web page using the <a> tag, an abbreviation for the anchor tag. A typical anchor tag looks like this:
<a href="http://demo-store.seleniumacademy.com/customer/account/" title="My Account">My Account</a>
Here, href is the link to a different page where your web browser will take you when you click on the link. So, the preceding HTML code when rendered by the browser looks like this:
This MY ACCOUNT is the link text. So the By.linkText locating mechanism uses this text on an anchor tag to identify the WebElement. The code would look like this:
@Test
public void byLinkTextLocatorExample() {
WebElement myAccountLink =
driver.findElement(By.linkText("MY ACCOUNT"));
myAccountLink.click();
assertThat(driver.getTitle())
.isEqualTo("Customer Login");
}
Here, the By.linkText locating mechanism is used to identify the MY ACCOUNT link.