Wednesday, December 24, 2014

Verify Image in Webpage using Selenium-Webdriver


In this example we are going to verify Image present in the webpage or not using 
JavaScript executor 

In this example am going to check the below scenario




Source Code :

import java.io.IOException;
import org.openqa.selenium.By;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.ie.InternetExplorerDriver;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;

public class Imageverify{
public static WebDriver driver;
@BeforeTest
public void startbrowser()
{
driver=new FirefoxDriver();
driver.get("http://automationplace.blogspot.in/");
}
@Test
public void imageverify()
{
WebElement ImageFile = driver.findElement(By.xpath("//*[@id='Profile1']/div/a[1]/img"));
       
       Boolean ImagePresent = (Boolean) ((JavascriptExecutor)driver).executeScript("return arguments[0].complete && typeof arguments[0].naturalWidth != \"undefined\" && arguments[0].naturalWidth > 0", ImageFile);
       if (!ImagePresent)
       {
            System.out.println("Image not displayed.");
       }
       else
       {
           System.out.println("Image displayed.");
       }
}
@AfterMethod
public void end()
{
driver.quit();
}

}


JavaScript executor Explanation:

Well, as far as I can see arguments[0] references an HTMLImageElement. That object has a complete property which indicates that the image is loaded or not. It also has naturalHeight and naturalWidth properties which together specifies the intrinsic size of the image once loaded. If these properties aren't available, they return 0.
Using what we just learned we can easily see how the following code will determine if the image is loaded or not:
return arguments[0].complete 
    && typeof arguments[0].naturalWidth != 'undefined' 
    && arguments[0].naturalWidth > 0; 
However, there's only the second condition involving checking for undefined that doesn't seem to be in line with what MDN says, since naturalWidth should be 0 when unavailable, not undefined.


Hope you like this post.
Hit LIKE button on facebook..






1 comment:

  1. Great efforts put it to find the list of articles useful for Selenium, Definitely will share the same to other forums.
    We are also one of the best sources to learn Selnium -Selenium Training Institute in chennai

    ReplyDelete