如何使用 Selenium 檢查頁面上是否顯示影像?


我們可以使用 Selenium 檢查頁面上是否顯示影像。為了驗證影像,我們需要藉助 Javascript Executor。我們將使用 executeScript 方法在 Selenium 中執行 Javascript 命令。

然後,將命令 return arguments[0].complete && typeof arguments[0].naturalWidth != \"undefined\" && arguments[0].naturalWidth > 0 作為該方法的引數進行傳遞。此外,必須在程式碼中新增語句 import org.openqa.selenium.JavascriptExecutor

語法

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);

讓我們檢查下面這個影像是否出現在頁面上 −

示例

程式碼實現。

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://tutorialspoint.tw/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();
   }
}

輸出

更新於: 28-Dec-2020

11K+ 次瀏覽

開啟你的 職業生涯

完成課程獲得認證

開始
廣告