获取颜色的方式有更多选择。
注意两种不同的颜色数据类型:
org.openqa.selenium.support.Color 与 java.awt.Color
Color color = Color.fromString(cssColorString); // for selenium Color
或
String[] rgba = cssColorString.replace("rgba(", "").replace(")", "").split(", ");
int r = Integer.parseInt(rgba[0]);
int g = Integer.parseInt(rgba[1]);
int b = Integer.parseInt(rgba[2]);
int a = Integer.parseInt(rgba[3]);
Color color2 = new Color(r, g, b, a); // for any of the two classes
完整代码示例:
package selenium;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.Color;
public class RaduRaspopa extends WebDriverSetup {
public static void main(String[] args) {
WebDriver driver = startChromeDriver(); // wrapped driver init
driver.get("https://www.toolsqa.com/");
WebElement advertisementImage = driver.findElement(By.id("advertisement-image"));
String cssColorString = advertisementImage.getCssValue("color");
Color color = Color.fromString(cssColorString);
System.out.println(color.asHex());
String[] rgba = cssColorString.replace("rgba(", "").replace(")", "").split(", ");
int r = Integer.parseInt(rgba[0]);
int g = Integer.parseInt(rgba[1]);
int b = Integer.parseInt(rgba[2]);
int a = Integer.parseInt(rgba[3]);
Color color2 = new Color(r, g, b, a);
System.out.println(color2.asHex());
driver.quit();
}
}
输出:
Starting ChromeDriver 96.0.4664.45 (76e4c1bb2ab4671b8beba3444e61c0f17584b2fc-refs/branch-heads/4664@{#947}) on port 25710
Only local connections are allowed.
Please see https://chromedriver.chromium.org/security-considerations for suggestions on keeping ChromeDriver safe.
ChromeDriver was started successfully.
Led 06, 2022 3:49:31 ODP. org.openqa.selenium.remote.ProtocolHandshake createSession
INFO: Detected dialect: W3C
#007bff
#007bff