9

次のコードでは、colorinを出力する必要がありますHex format

最初の Print ステートメントは、 のRGB形式で値を表示していますrgb(102,102,102)

2 番目のステートメントは値を示してHex います。#666666

しかし、2 番目の print ステートメントに手動で値を入力しています102,102,102

最初のステートメント (Color) から取得した値を 2 番目の print ステートメントに渡して結果を取得する方法はありますか?

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

4 に答える 4

9

方法 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);
于 2014-01-23T11:51:43.507 に答える
4

コードは機能しますが、ほんの少しのタイプミスです。Color.fromString は大文字の C になります

import org.openqa.selenium.support.Color;

String color = driver.findElement(By.xpath("xpath_value")).getCssValue("color");
System.out.println(color);
String hex = Color.fromString(color).asHex();
System.out.println(hex);
于 2017-05-23T20:08:05.737 に答える