How to count the total number of links in a page in Selenium?

The total number of links in a page can be counted with the help of findElements() method. The logic is to return a list of web elements with tagname anchor, then getting the size of that list.

Code Implementation


import org.openqa.selenium.By;
import org.openqa.selenium.Keys;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import java.util.concurrent.TimeUnit;
public class LinkCount {
   public static void main(String[] args) {
      System.setProperty("", "C:\Users\ghs6kor\Desktop\Java\chromedriver.exe");
      WebDriver driver = new ChromeDriver();
      String url = "";
      driver.manage().timeouts().implicitlyWait(12, TimeUnit.SECONDS);
      //Using tagname with anchor
      List<WebElement> links = driver.findElements(By.tagName("a"));
      System.out.println(“The number of links is “ + links.size());

Updated on: 10-Jun-2020

12K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started