如何在 Selenium Webdriver 中驗證 Web 元素的顏色?


我們可以使用 getCssValue 方法在 Selenium webdriver 中驗證 Web 元素的顏色,然後將顏色作為引數傳遞給它。這將以 rgba() 格式返回顏色。

接下來,我們必須使用 Color 類將 rgba() 格式轉換為 Hex。讓我們獲取下面圖片中突出顯示的元素的顏色。相應的元素顏色在 Chrome 瀏覽器的“樣式”選項卡中。該元素顏色還以十六進位制程式碼 #797979 提供。

元素的顏色也以十六進位制程式碼 #797979 提供。

語法

WebElement t = driver.findElement(By.tagName("h1"));
String s = t.getCssValue("color");
String c = Color.fromString(s).asHex();

示例

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.support.Color;
public VerifyColor{
   public static void main(String[] args) {
      System.setProperty("webdriver.chrome.driver", "C:\Users\ghs6kor\Desktop\Java\chromedriver.exe");
      WebDriver driver = new ChromeDriver();
      driver.get("https://tutorialspoint.tw/about/about_careers.htm");
      // identify text
      WebElement t = driver.findElement(By.tagName("h1"));
      //obtain color in rgba
      String s = t.getCssValue("color");
      // convert rgba to hex
      String c = Color.fromString(s).asHex();
      System.out.println("Color is :" + s);
      System.out.println("Hex code for color:" + c);
      driver.quit();
   }
}

輸出

更新於:2021 年 4 月 3 日

23K+ 瀏覽量

開啟 職業生涯

完成課程認證

開始
廣告