Verify all links on a Webpage using Selenium Webdriver

As an automation tester, you get to play with links present on the website. Links are one of the most important part of the webpage. Some times we need to check which links are present on the page and some times to verify all the links are working.

Luckily, Selenium Webdriver has the flexibility to do both the things. Otherwise it could be a tedious task to check manually that all the links present on a webpage are working or not.

Code to Get All Links from a Web page

public class FindAllLinks {
 
 public static void main(String[] args) {

 // Initialize Webdriver Object
 System.setProperty("webdriver.chrome.driver", "D:\\mydir\\chromedriver.exe");
 WebDriver driver = new ChromeDriver();

 driver.get("http://techlistic.com/");

 // Store all link elements (anchor tag elements in html) in a list
 java.util.List links = driver.findElements(By.tagName("a"));

 // Print no. of links stored in list
 System.out.println(links.size());

 for (int i = 1; i<=links.size(); i=i+1)
  {

  // Print text of all the links
  System.out.println(links.get(i).getText());

  }

 }
 
}

Code Explanation:

1. Open the webpage.
2. Create a list of type WebElements' and store all elements with tagname 'a' in it using 'findElements()'
3. Iterate over all the links using list size as it's maximum value.
4. Get the text of the link by using getText() and print it.

Now, you have all the links in the list, you can perform different operations on it and put different checks on it. 

Happy Learning!

Webdriver Script (All basic commands) << Previous     ||     Next >>  Handle Alerts or Pop-ups


Follow Us

Quora Space | Facebook Page | Telegram Channel
Feel free to ask queries or share your thoughts in comments or email us.

Comments

Popular posts from this blog

10 Best Demo Websites for Automation Testing Practice

Automate 'User Registration' of E-commerce Website using Selenium

Selenium WebDriver Browser and Navigation Commands

Automate 'Buy Product' from E-commerce Website using Selenium