Posts Tagged ‘size’

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