
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Check if an Image is Displayed on Page Using Selenium
We can check if an image is displayed on page with Selenium. To verify an image we shall take the help of Javascript Executor. We shall utilize executeScript method to execute the Javascript commands in Selenium.
Then pass the command return arguments[0].complete && typeof arguments[0].naturalWidth != \"undefined\" && arguments[0].naturalWidth > 0 as a parameter to that method. Moreover, the statement import org.openqa.selenium.JavascriptExecutor has to be added in code.
Syntax
WebElement i = driver.findElement(By.xpath("//img[@title='Tutorialspoint']")); Boolean p = (Boolean) ((JavascriptExecutor)driver) .executeScript("return arguments[0].complete " + "&& typeof arguments[0].naturalWidth != \"undefined\" " + "&& arguments[0].naturalWidth > 0", i);
Let us check if the below image is present on page −
Example
Code Implementation.
import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.chrome.ChromeDriver; import java.util.concurrent.TimeUnit; import org.openqa.selenium.JavascriptExecutor; public class ImageChk{ public static void main(String[] args) { System.setProperty("webdriver.chrome.driver", "C:\Users\ghs6kor\Desktop\Java\chromedriver.exe"); WebDriver driver = new ChromeDriver(); driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS); String url = "https://www.tutorialspoint.com/index.htm"; driver.get(url); //identify image WebElement i = driver.findElement (By.xpath("//img[@title='Tutorialspoint']")); // Javascript executor to check image Boolean p = (Boolean) ((JavascriptExecutor)driver) .executeScript("return arguments[0].complete " + "&& typeof arguments[0].naturalWidth != \"undefined\" " + "&& arguments[0].naturalWidth > 0", i); //verify if status is true if (p) { System.out.println("Logo present"); } else { System.out.println("Logo not present"); } driver.quit(); } }
Output
Advertisements