Find Broken Images for an Application or a Website(WebDriver) - Bug Reaper

                  Bug Reaper

Lean about Automation Testing,Selenium WebDriver,RestAssured,Appium,Jenkins,JAVA,API Automation,TestNG,Maven, Rest API, SOAP API,Linux,Maven,Security Testing,Interview Questions

Tuesday 24 September 2013

Find Broken Images for an Application or a Website(WebDriver)

Code in Selenium to Find Broken Images for an Application or a Website

import java.util.List;
import java.util.concurrent.TimeUnit;

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

public class testbroken {

WebDriver myFD = new FirefoxDriver();
String vURL = "http://richardjdavis.blogspot.in/";//Using Sample Website as it contains one Broken Image
@Test
public void checkforbrokenimages() throws Exception{

myFD.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
myFD.get(vURL); 
//myFD.findElement(By.name("q")).sendKeys("Test"); 

List<WebElement> imagesList = myFD.findElements(By.tagName("img"));
int countBrokenImages = 0;
for (WebElement image : imagesList)
{
HttpResponse response = new DefaultHttpClient().execute(new HttpGet(image.getAttribute("src")));
if (response.getStatusLine().getStatusCode() != 200){
// Do whatever you want with broken images
String currentImageUrl = image.getAttribute("src");
System.out.println(currentImageUrl);
countBrokenImages++;
}
System.out.println("The number of Broken URLs are: " + countBrokenImages);
}
}

3 comments:

  1. If we want to found broken links in the webpage then how friend????????

    ReplyDelete
  2. why cant we make static to countBrokenImages??

    ReplyDelete
  3. my question is, if we have a protect image, is possible check it with the url?

    ReplyDelete