I need to automate (using selenium) for missing images on a webpage. Now an image can be loaded in three ways: 1)
<img src="http://something.com/google.png">
2)
<img src="/path/to/file/image.jpg">
3)
<div class="someIcon" autoID="some-icon"></div>
The above info can come from a CSS (for example
.someIcon {
height: 97px;
width: 93px;
background-image: url("../assets/images/some_icon.png");
background-size: 93px 97px;
}
Now with these different way of loading images on a html page, how can I write automation to identify whether an image is missing or not?
Problem 1) can be solved using
List<WebElement> imagesList = _driver.findElements(By.tagName("img"));
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
}
How about 2) & 3) ?
Thanks, Mateen
In second case the value of src will be resolved to full URL, so you can use the same method as with first case.
For third case you need to get value of background-image
by calling getCssValue
. However the return value will be in form of url("http://<server>/assets/images/some_icon.png")
so you will need to parse it:
WebElement div = driver.findElement(By.className("someIcon"));
String bgImage = div.getCssValue("background-image");
Matcher m = Pattern.compile("\\\".*\\\"").matcher(bgImage);
if (m.find()) {
String imgUrl = m.group().replace('"', ' ').trim();
// verify imgUrl
}