Finding Out All Links In A Webpage

In many cases, we find scenarios where we have to collect all the links in a webpage and have to perform some operation – like checking if the links are clickable or not. To do so we need to find out all links in a webpage, put them in a list and then do that operation.

In this program, I am going to take a webpage, print out the total number of links in the page and then print the link text of the links.

We find elements using the tagname “a” and then create a list and put the elements in it. Then we iterate through that list and print the link text simultaneously.


public class AllLinkText {
private WebDriver driver;
private String baseUrl;
@Test
public void f() {
driver.get(baseUrl);

//putting all elements in list
List<WebElement> lists = driver.findElements(By.tagName("a"));
System.out.println(lists.size());

//printing size of links
int n=lists.size();

//iterating through the list and getting link text
for(int i=0;i<=n;i++){
System.out.println(lists.get(i).getText());
}

}
@BeforeTest
public void beforeTest() {
driver=new FirefoxDriver();
baseUrl="http://istqbexamcertification.com/what-is-a-defect-life-cycle/";
driver.manage().window().maximize();
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
}

@AfterTest
public void afterTest() {
driver.quit();
}

}

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.