一尘不染

Selenium WebDriver中十六进制格式的getCssValue(颜色)

selenium

在以下代码中,我需要打印colorin Hex format

第一个 Print语句以RGB格式显示值rgb(102,102,102)

第二个 语句显示值在Hex 其中#666666

但是,我正在手动将值输入到第二个打印语句中102,102,102

有什么方法可以将我从第一个语句(颜色)获得的值传递到第二个打印语句并获得结果?

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;

public class Google {

    public static void main(String[] args) throws Exception {

        WebDriver driver = new FirefoxDriver();
        driver.get("http://www.google.com/");
        String Color = driver.findElement(By.xpath("//div[@class='gb_e gb_f gb_g gb_xb']/a")).getCssValue("color");
        System.out.println(Color);
        String hex = String.format("#%02x%02x%02x", 102,102,102);
        System.out.println(hex);
    }
}

阅读 492

收藏
2020-06-26

共1个答案

一尘不染

方法1:使用StringTokenizer:

String color = driver.findElement(By.xpath("//div[@class='gb_e gb_f gb_g gb_xb']/a")).getCssValue("color");
String s1 = color.substring(4);
color = s1.replace(')', ' ');
StringTokenizer st = new StringTokenizer(color);
int r = Integer.parseInt(st.nextToken(",").trim());
int g = Integer.parseInt(st.nextToken(",").trim());
int b = Integer.parseInt(st.nextToken(",").trim());
Color c = new Color(r, g, b);
String hex = "#"+Integer.toHexString(c.getRGB()).substring(2);
System.out.println(hex);

方式2:

String color = driver.findElement(By.xpath("//div[@class='gb_e gb_f gb_g gb_xb']/a")).getCssValue("color");
String[] numbers = color.replace("rgb(", "").replace(")", "").split(",");
int r = Integer.parseInt(numbers[0].trim());
int g = Integer.parseInt(numbers[1].trim());
int b = Integer.parseInt(numbers[2].trim());
System.out.println("r: " + r + "g: " + g + "b: " + b);
String hex = "#" + Integer.toHexString(r) + Integer.toHexString(g) + Integer.toHexString(b);
System.out.println(hex);
2020-06-26