Saturday, March 28, 2015

How to find Broken links in a Web page

package selenium;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;

     public class Brokenlinks {
         public static void main(String[] args) throws InterruptedException,
ClientProtocolException, IOException {
               WebDriver driver = new FirefoxDriver();
               driver.manage().window().maximize();
               driver.get("http://newtours.demoaut.com/");

           int size = driver.findElements(By.tagName("a")).size();
           System.out.println(size);
           List<String> Linkarray = new ArrayList<String>();
           List<WebElement> Links = driver.findElements(By.tagName("a"));

           for (WebElement image : Links)
           {
                      @SuppressWarnings("deprecation")
                    HttpResponse response = new DefaultHttpClient().execute(new HttpGet(image.getAttribute("href")));
                      String links = image.getText();
                    Linkarray.add(links );

                    Thread.sleep(200);
                    if (response.getStatusLine().getStatusCode() != 404)

               {
                                    System.out.println("pass : "+ links);
               }
                    else if(response.getStatusLine().getStatusCode() == 404 )
               {
                   System.out.println("fail"+ links);

               }

                    } driver.close();
             }}

No comments:

Post a Comment

TestNG - Can i use the 2 different data providers to same @test methods in TestNG?

public Object [][] dp1 () { return new Object [][] { new Object [] { "a" , "b" }, new Obje...