Friday 20 June 2014

Checking all links are working(or) broken links program

package Webdriverprgs;

import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
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;
import org.testng.annotations.Test;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.AfterTest;

public class checkinglinks {
    public WebDriver driver;
      @Test
      public void f() throws IOException {
          List<WebElement>str= driver.findElements(By.tagName("a"));
          for (int i = 0; i < str.size(); i++) {
              System.out.println(str.get(i).getText());
          }
              for(WebElement linkElement: str){
                    String link = linkElement.getAttribute("href");
                    System.out.println(link);
                 
              if(link!=null){
                  if(!isLink(link)){
                      continue;
                  }
                 
             }
             
              verifyLinkActive(link);
              }
      }
     
      public static void verifyLinkActive(String linkUrl) throws IOException{
          try {
              URL url = new URL(linkUrl);
              HttpURLConnection httpURLConnect = (HttpURLConnection)url.openConnection();
              httpURLConnect.setConnectTimeout(3000);
              httpURLConnect.connect();
              if(httpURLConnect.getResponseCode()==HttpURLConnection.HTTP_NOT_FOUND){
                  System.out.println(linkUrl+"-"+httpURLConnect.getResponseMessage()+"-"+
              HttpURLConnection.HTTP_NOT_FOUND);
              }
          } catch (MalformedURLException e) {
              e.printStackTrace();
          }
      }
      private boolean isLink(String link) {
        // TODO Auto-generated method stub
        return false;
    }
    @BeforeTest
      public void beforeTest() {
          driver=new FirefoxDriver();
          driver.get("http://flipkart.com");
          driver.manage().window().maximize();
      }

      @AfterTest
      public void afterTest() {
      }

    }

No comments:

Post a Comment