Open In App

How to Get All Available Links on the Page using Selenium in Java?

Last Updated : 23 Apr, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

Selenium is an open-source Web-Automation tool that is used to automate web Browser Testing. The major advantage of using selenium is, that it supports all major web browsers and works on all major Operating Systems, and it supports writing scripts on various languages such as Java,  JavaScript, C# and Python, etc. While automating a webpage, we are required to fetch and check all the available links present on the webpage, In this article, we will learn to get all the available links present on a page using “TagName”.

As we know all the links are of type anchor tag “a” in HTML. For Example,

<a href=”geeksforgeeks.org”>geeksforgeeks</a>

  • Navigate to the webpage.
  • Get the list of WebElements with the TagName “a”.
  • List<WebElement> links=driver.findElements(By.tagName(“a”));
  • Iterate through the List of WebElements.
  • Print the link text.

In this example, we are navigating to the URL “https://www.geeksforgeeks.org/” and print the link text of all available links on the page.

Java
public class Geeks {

    WebDriverManager.chromedriver().setup();
    WebDriver driver = new ChromeDriver();
    driver.manage().window().maximize();
    driver.get("https://www.geeksforgeeks.org/");

    // Get all the available Links
    List<WebElement> links
        = driver.findElements(By.tagName("a"));

    // Iterating through all the Links and printing link
    // text
    for (WebElement link : links) {
        System.out.println(link.getText());
    }

    driver.close();
}

Output:

This program will get all the Links in the List of WebElements and print all the link texts.


Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads