2

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

4

1 回答 1

0

在第二种情况下,src 的值将被解析为完整的 URL,因此您可以使用与第一种情况相同的方法。

对于第三种情况,您需要background-image通过调用getCssValue. 但是,返回值将采用以下形式,url("http://<server>/assets/images/some_icon.png")因此您需要对其进行解析:

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
}
于 2014-09-24T10:49:58.410 回答