I want to assert that an image is present on a page. I'm using selenium web driver with python. I also want a message printed when the image has not been loaded. Can anyone help me with a script?
Here is a piece of html code that displays an image on a website: [img src='photo.jpg' class='image class']
I can't help with python, but can give a general suggestion and Java code for those who are looking to do something similar in Java. My approach would be
src attribute of the image and make a quick HTTP GET
call and make sure you get 200 OK response.naturalWidthattribute of the WebElement using
Javascript. If its more than 0, its rendered fine. However this
works differently in IE. IE has .complete attribute. It will be
true if the image is rendered (Reference here)Here is sample Java code,
@Test
public void test()
{
WebDriver driver = new FirefoxDriver();
String url = "http://www.espncricinfo.com/";
driver.get(url);
WebElement img = driver.findElement(By.cssSelector("a[title='ESPN Cricinfo']>img"));
String src = img.getAttribute("src");
Client client = Client.create();
WebResource resource = client.resource(src);
assertThat("Response code is not 200 OK", resource.get(ClientResponse.class).getStatus(), equalTo(200));
assertThat("Image is not rendered correctly", isImageVisible(driver, img),equalTo(true));
driver.quit();
}
public boolean isImageVisible(WebDriver driver, WebElement image)
{
Boolean result = null;
if (driver instanceof InternetExplorerDriver || ((RemoteWebDriver) driver).getCapabilities().getBrowserName().equals("internet explorer"))
{
result = (Boolean) ((JavascriptExecutor) driver).executeScript("return arguments[0].complete;", image);
}
else
{ //other browser types use diff method to check
result = (Boolean) ((JavascriptExecutor) driver).executeScript("return (typeof arguments[0].naturalWidth!=\"undefined\" && arguments[0].naturalWidth>0);", image);
}
return result.booleanValue();
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With