Thursday, 4 February 2016

How to find Broken or Invalid Images on a WebPage using selenium webdriver

How to find Broken or  Invalid Images on a Web Page using selenium web driver:
=============================================================

package blog;

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

import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.HttpClientBuilder;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.ie.InternetExplorerDriver;
import org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;

public class FindBrokenImages {

private WebDriver webDriver;
private int invalidImageCount;

@BeforeClass
public void setUp() {
System.setProperty("webdriver.chrome.driver",
"D:\\Ramesh\\ChromeDriver.exe");
webDriver = new InternetExplorerDriver();
// webDriver=new FirefoxDriver();
webDriver.manage().window().maximize();
webDriver.manage().deleteAllCookies();
webDriver.manage().timeouts().implicitlyWait(45, TimeUnit.SECONDS);
}

@Test
public void validateInvalidImages() throws ClientProtocolException,
IOException, InterruptedException {

webDriver.get("https://google.com");
webDriver.findElement(By.name("q")).sendKeys("selenium by ramesh");
webDriver.findElement(By.name("btnG")).click();
Thread.sleep(3000);
webDriver.findElement(By.linkText("Selenium By Ramesh Anapati"))
.click();

invalidImageCount = 0;
List<WebElement> imagesList = webDriver.findElements(By.tagName("img"));
System.out.println("Total number of images are " + imagesList.size());
for (WebElement image : imagesList) {
if (image != null) {
validateImage(image);
}
}
System.out.println("Total number of of invalid images are "
+ invalidImageCount);

}

public void validateImage(WebElement imgElement)
throws ClientProtocolException, IOException {

HttpClient client = HttpClientBuilder.create().build();
HttpGet request = new HttpGet(imgElement.getAttribute("src"));
HttpResponse response = client.execute(request);
// verifying response code he HttpStatus should be 200 if not,
// increment as invalid images count
if (response.getStatusLine().getStatusCode() != 200)
invalidImageCount++;
}

@AfterClass
public void tearDown() {

webDriver.quit();
}


}

2 comments: