3

I have a http page. Can I verify any broken link when a page has no https link and mail address in the page body.

Is there any way to find the broken link using selenium webdriver in java, when page have multiple https links and mail address in page body ?

2 Answers 2

1
driver.get("Your page on which links are to be verified");
// Collect all the links into an element.
List<WebElement> links = driver.findElements(By.tagName("a"));
// For each link check repose code is 200.
for (WebElement link : links) {

    String value = link.getAttribute("href");
    // For each link check response code is 200.      
    URL myurl = new URL(value);        
    HttpURLConnection connection = (HttpURLConnection) myurl.openConnection();        
    connection.setRequestMethod("HEAD");         
    int code = connection.getResponseCode();        
    Assert.assertEquals(code, 200);

}
3
  • this code will work only when page have all http link nothing else. Your code have some error.I can not iterate WebElement links by assigning it string link.I explicitly mention that my page have https link(map) and mail link in (a contact page).
    – rahiktamim
    Commented Nov 28, 2016 at 6:39
  • you code have some fixes: <!-- language: c# --> List<WebElement> links = driver.findElements(By.tagName("a")); for (WebElement link : links) { System.out.println("link "+ link); String urlLinks=link.getAttribute("href"); System.out.println(urlLinks); URL myurl = new URL(urlLinks);
    – rahiktamim
    Commented Nov 28, 2016 at 6:56
  • Yup. sorry, I directly wrote code here, should have tested once :p .. updated the code, thanks hope this helped you :) Commented Nov 28, 2016 at 18:50
0

Can you not use this tool instead? Check my links

If you really want to use Java to detect broken links, below is a suggestion:

  1. Build your pages using Page Object Model
  2. Identify all of your elements that lead to links and the links' URL
  3. In your test, you can write something like, newURL = webdriver.link.click(), assert (newURL == expectedURL); this way you can know whether a link is broken.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.