Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check image requests for 404 using Selenium WebDriver?

What is the most convenient way using Selenium WebDriver to check if an URL GET returns successfully (HTTP 200)?

In this particular case I'm most interested in verifying that no images of the current page are broken.

like image 300
stpe Avatar asked Sep 21 '09 09:09

stpe


People also ask

How check image is displayed or not in Selenium?

We can check if an image is displayed on page with Selenium. To verify an image we shall take the help of Javascript Executor. We shall utilize executeScript method to execute the Javascript commands in Selenium. Then pass the command return arguments[0].

How do I find an image in Selenium?

We can get the source of an image in Selenium. An image in an html document has <img> tagname. Each image also has an attribute src which contains the source of image in the page. To fetch any attribute in Selenium, we have to use the getAttribute() method.


2 Answers

Try this:

List<WebElement> allImages = driver.findElements(By.tagName("img"));
for (WebElement image : allImages) {
  boolean loaded = ((JavaScriptExecutor) driver).executeScript(
      "return arguments[0].complete", image);
  if (!loaded) {
    // Your error handling here.
  }
}
like image 60
Simon Stewart Avatar answered Oct 24 '22 08:10

Simon Stewart


You could use the getEval command to verify the value returned from the following JavaScript for each image on the page.

@Test
public void checkForBrokenImages() {
    selenium.open("http://www.example.com/");
    int imageCount = selenium.getXpathCount("//img").intValue();
    for (int i = 0; i < imageCount; i++) {
        String currentImage = "this.browserbot.getUserWindow().document.images[" + i + "]";
        assertEquals(selenium.getEval("(!" + currentImage + ".complete) ? false : !(typeof " + currentImage + ".naturalWidth != \"undefined\" && " + currentImage + ".naturalWidth == 0);"), "true", "Broken image: " + selenium.getEval(currentImage + ".src"));
    }
}

Updated:

Added tested TestNG/Java example.

like image 23
Dave Hunt Avatar answered Oct 24 '22 06:10

Dave Hunt