Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
853 views
in Technique[技术] by (71.8m points)

java - getCssValue (Color) in Hex format in Selenium WebDriver

In the following code I need to print the color in Hex format.

First Print statement is showing value in RGB format which is rgb(102,102,102).

The Second statement is showing value in Hex which is #666666

But I am manually entering the value into the second print statement which is 102,102,102.

Is there any way to pass the value which I got from the 1st statement (Color) into the second print statement and get result?

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);
    }
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

I know this is rather old, but you can get a simpler solution by using org.openqa.selenium.support.Color:

import org.openqa.selenium.support.Color;
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 = Color.fromString(color).asHex();
System.out.println(hex);

It gives you a single line solution and even adds leading zeroes when required (something that the previous answers aren't accounting for)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...