Wednesday 8 February 2017

SELENIUM: How to Verify a link is broken or not


How to Verify a link is broken or not

What is broken link:
whenever we get 404 page not found an issue in most of the application which is called broken link.
we can identify that we need to  find broken links using selenium it means we need to check the link which is pointing to wrong URL or invalid URL.
While doing validation you have to verify only  status is 20
Example:
package com.rameshsoft.rameshselenium;

import java.net.HttpURLConnection;
import java.net.URL;
import java.util.List;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;

public class ValidatingLinksDemo {

          public static void main(String[] args) throws InterruptedException
          {
                   System.setProperty("webdriver.gecko.driver", "C:\\Users\\ramesh\\Desktop\\java\\desk\\geckodriver-v0.11.1-win64\\geckodriver.exe");

                   WebDriver driver=new FirefoxDriver();
                  
                   driver.manage().window().maximize();
                  
                   driver.get("https://www.google.com");
                   Thread.sleep(5000);
List<WebElement> links=driver.findElements(By.tagName("a"));
                  
                   System.out.println("Total links are "+links.size());
                  
                   for(int i=0;i<links.size();i++)
                   {
                            
                             WebElement ele= links.get(i);
                            
                             String url=ele.getAttribute("href");
                            
                             verifyLink(url);
                            
                   }
                   driver.quit();
                  
          }
         
          public static void verifyLink(String link_Url)
          {
        try
        {
           URL url = new URL(link_Url);
          
           HttpURLConnection httpURLConnect=(HttpURLConnection)url.openConnection();
          
           httpURLConnect.setConnectTimeout(3000);
          
           httpURLConnect.connect();
          
           if(httpURLConnect.getResponseCode()==200)
           {
               System.out.println(link_Url+" - "+httpURLConnect.getResponseMessage());
            }
          if(httpURLConnect.getResponseCode()==HttpURLConnection.HTTP_NOT_FOUND) 
           {
               System.out.println(link_Url+" - "+httpURLConnect.getResponseMessage() + " - "+ HttpURLConnection.HTTP_NOT_FOUND);
            }
        } catch (Exception e) {
          System.out.println(e.getMessage());

}
}
}

No comments:

Post a Comment