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

Example

import org.openqa.selenium.By;
import org.openqa.selenium.Keys;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import java.util.concurrent.TimeUnit;
public class LinkCount {
   public static void main(String[] args) {
      System.setProperty("webdriver.chrome.driver", "C:\Users\ghs6kor\Desktop\Java\chromedriver.exe");
      WebDriver driver = new ChromeDriver();
      String url = "https://www.tutorialspoint.com/index.htm";
      driver.get(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());
      driver.close();
   }
}

Updated on: 10-Jun-2020

11K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements