With selenium can one run a test which check all images on a current page if they contain ALT attribute and report images not having it ?
3 Answers
Yes. The first thing you need to do is decide which selenium you want to use.
- You can use Selenium IDE, where a test consists of an HTML table.
- You can use Selenium RC, where you write a test in a programming language (eg. C#, Java, PHP, Ruby, etc).
The latter is a little more complex at first, but if you want real power, you will use that method.
Then, you'll need to learn how to find all the images on a page.
//img
is a good XPath query to use. For Xpath details, see w3schools, and especially this page.
Then you'll want to find images with an alt attribute: //img[@alt]
One approach would be to count how many images there are, and subtract the number with alt attributes.

- 6,701
- 3
- 34
- 56
-
1After some reading I found out that you can locate all images that don't have an ALT attribute with using the xpath expression //img[not(@alt)] – bananmuffins Mar 23 '10 at 11:28
You can also do this in WebDriver (soon to be Selenium 2). The following example is for TestNG/Java but other client languages are available.
List<WebElement> images = driver.findElements(By.xpath("//img[not(@alt)]"));
assertEquals(images.size(), 0);
For more feedback you could also use something like the following to output details of the images without alt attributes:
for(WebElement image : images) {
System.out.println(image.getAttribute("src"));
}

- 8,191
- 4
- 38
- 39
We have a similar test but we grab the page's Html and parse out the images with a regular expression and then match on a second regular expression looking for the alt tag. I haven't done a speed test, but I think it might be faster than doing the Xpath route.

- 3,259
- 3
- 19
- 10