</>

Technology

Selenium

Difficulty

Beginner

Interview Question

How can we find all the links on a web page using Selenium?

All hyperlinks use the anchor tag <a>. Use findElements(By.tagName("a")) to get all links on a page.

Answer

All hyperlinks on a web page use the HTML anchor tag <a>. Use findElements(By.tagName("a")) to retrieve all links at once.

Get all links:

Java
List<WebElement> links = driver.findElements(By.tagName("a"));
System.out.println("Total links: " + links.size());

Print all link texts and URLs:

Java
List<WebElement> links = driver.findElements(By.tagName("a"));
for (WebElement link : links) {
    System.out.println("Text: " + link.getText());
    System.out.println("URL:  " + link.getAttribute("href"));
    System.out.println("---");
}

Check for broken links (HTTP status):

Java
List<WebElement> links = driver.findElements(By.tagName("a"));
for (WebElement link : links) {
    String url = link.getAttribute("href");
    if (url != null && !url.isEmpty()) {
        HttpURLConnection conn = (HttpURLConnection) new URL(url).openConnection();
        conn.setRequestMethod("HEAD");
        conn.connect();
        int responseCode = conn.getResponseCode();
        if (responseCode >= 400) {
            System.out.println("Broken link: " + url + " | Code: " + responseCode);
        }
    }
}

Filter only visible links:

Java
links.stream()
     .filter(WebElement::isDisplayed)
     .forEach(l -> System.out.println(l.getText()));

Follow AutomateQA

Related Topics