How can we find all links in a website other than home page using java selenium

207 Views Asked by At

I want to get all links with its response code in a website other than home page. I have tried using findElements method with anchor tag but this gives me links on home page only. Now suppose i have some menus also in that home page and i want to get links associated with that pages also. Is it possible??

2

There are 2 best solutions below

0
On

Using this you can collect links from a page.

List<WebElement> aTags = driver.findElements(By.tagName("a");
List<String> links = new ArrayList<String>();
for (WebElement aTag: aTags) {
    links.add(aTag.getAttribute("href");
}

For all links they are not file links, you can loop this as well. Another thing is to check the response code, see https://www.baeldung.com/java-http-request.

0
On

To get all active links present in webpage please try below code. If possible please share your test URL and code, then I can replicate it from my side.

 List<WebElement> linksList = driver.findElements(By.tagName("img"));
 linksList.addAll(driver.findElements(By.tagName("a")));
 System.out.println("The full size of Links and Images are: "+linksList.size());
 List<WebElement> activeLinks = new ArrayList<WebElement>();
 for(int i=0; i<linksList.size(); i++) {
 Thread.sleep(200);
 System.out.println(linksList.get(i).getAttribute("href"));
    if(linksList.get(i).getAttribute("href") != null) {
        activeLinks.add(linksList.get(i));
    }
    }