Clicking a Link By Text, ID, and XPath

Build on the fundamentals of Selenium by learning how to locate hyperlinks.

Click a link by text

Probably the most direct way to click on a link in Selenium is by using text in the web page. For that, we use linkText as follows:

driver.findElement(By.linkText("Recommend Selenium")).click();

Click a link by partial text

We can achieve the similar goal even if we just work with the partial text as shown below:

driver.findElement(By.id("recommend_selenium_link")).click();

Click a link by ID

Although working with the text is very straightforward, there is, however, a downside to this. For instance, what happens if a web page consists of multiple languages, say Chinese or Italian mixed with English? Then we could easily find ourselves writing a script like:

if (isItalian()) {
  driver.findElement(By.linkText("Accedi")).click();  
} else if (isChinese()) { // a helper function determines the locale
  driver.findElement(By.linkText, "登录").click();
} else {
  driver.findElement(By.linkText("Sign in")).click();
}

To avoid such scenarios, we can use another way by using IDs:

driver.findElement(By.id("recommend_selenium_link")).click();

Using id is the most feasible option while working on a site with multiple languages.

Click a link by XPath

In addition to these, another way of doing a similar job is by using XPath:

driver.findElement(By.xpath( "//p/a[text()='Recommend Selenium']")).click();

Here, it is finding a link with the text Recommend Selenium under a <p> tag.

Get hands-on with 1400+ tech skills courses.