How to extract no. of links and text of links present on a page in Selenium WebDriver

Posted: January 19, 2013 in Automation, selenium
Tags: , , , , , , ,

How to extract no. of links and text of  links present on a page in Selenium WebDriver:

We all know that tag name for every link starts with letter “a”. “a” refers to the anchor tag. The tag name which starts with letter “a” should be a link.

Because all links has tag name “a” so we can identify links with tagName method of By class i.e.

driver.findElements(By.tagName(“a”));

To find the total no of links on a page:

Suppose you want to find total no. of links on google page for this you can use

driver.get(“http://www.google.com”);

List<WebElement> alllinkspresent=driver.findElements(By.tagName(“a”));

System.out.println(“no. of links on google page are :” +alllinkspresent.size());

Where size() method returns the total no of links on Google page.

To find or print the name of links i.e. text of links:

Suppose you want to print text of all links present on Google page for this you can use

for(int i=0; i< alllinkspresent.size(); i++)

{

System.out.println(alllinkspresent.get(i).getText());

}

To extract the links of a particular section:

Suppose you want to extract the links of languages offered by Google section for this you can use

WebElement LangSection=driver.findElement(By.xpath (“//*[@id=’addlang’]”));

List<WebElement> lang=LangSection.findElements(By.tagName(“a”));

for(int i=0; i< lang.size(); i++)

{

System.out.println(lang.get(i).getText());

}

Where LangSection is one WebElement and we have to find the all the links present in this section. For understanding of this section of code please refer following screen shot

When you run the above code you will get text of all links present in this section. Refer following screen shot

Comments
  1. nice article and you have made this so easy to assimilate…

  2. Amrit says:

    Great stuff!!

  3. sunil says:

    But it is not working properly

  4. Anshul says:

    helpfull

  5. Rajamurugan says:

    HI, i jus wan to verify the link present on page or not, can you plz help me on that

  6. balaji says:

    hi am new to selenium webdriver i have error in checking all the sublinks of the website from excel sheet using data driven method it does not take more than two urls from excel sheet and also have error like cannot finf linkstext

  7. phaneedra says:

    Thanks for good explanation. Iam trying to get link only not the text(which is clickable). Say in ur example it prints hindi, english …. texts from google but Iam looking for href of that text. Please let me know How can we do that.

Leave a comment