如何在Selenium WebDriver中验证文本颜色?

4

我有一个web应用程序。

使用selenium webdriver编写自动化脚本。

当我选择一些文本时,我会写一些颜色代码。

现在我想检查是否存在颜色代码。

在selenium webdriver脚本中如何验证颜色代码?


尝试使用String color = driver.findElement(By.id("foo")).getCssValue("color");。我不确定这是否适用于您的情况。 - Hai Lu
谢谢,但这个情况下它不起作用。 - Sagar007
6个回答

2

绿色的哈希代码 #RRGGBB: #008000 // 测试数据,可以更改为任何特定的颜色

可以尝试以下代码:

String colorString = driver.findElement(By.id("foo")).getAttribute("class");
String[] arrColor = colorString .split("#");
assertTrue(arrColor[1].equals("008000"));

2
WebElement eleSearch = driver.findElement(By.xpath("//*[@class='navsearchbar']//div[2]//div"));

String rgbFormat = eleSearch.getCssValue("background-color");

System.out.println(rgbFormat);     //In RGB Format the value will be print => rgba(254, 189, 105, 1)

String hexcolor = Color.fromString(rgbFormat).asHex(); //converted Into HexFormat
System.out.println(hexcolor);// Output of Hex code will be  => #febd69

1
使用Java类Color,因为getCSSValue以RGBA格式返回颜色。
Assertions.assertTrue(Color.fromString("#000000").equals(Color.fromString(yourWebelement.getCssValue("color"))), "Text 'fieldName' color");

1
你可以使用 .getCssValue 来获取颜色值。
根据您的要求,如果您想验证颜色,您可以进行断言,类似于以下内容:
assertTrue(selenium.isElementPresent("css=td[bgcolor=#000]"));

实际上它没有CSS值。它在选择后才会给出颜色。 - Sagar007
这是一个链接文本还是其他内容?请提供更多信息。 - Vignesh Paramasivam
这是简单的文本。但现在我想检查它的颜色代码。 - Sagar007
我会尝试您的解决方案。如果我成功找到它的CSS,我会告诉您。 - Sagar007

1

经过尝试不同的脚本,最终我找到了我的问题的答案。

String colorString = driver.findElement(By.id("foo")).getAttribute("class");
String[] arrColor = colorString .split("#");
assertTrue(arrColor[1].equals("FFFFFF"));

Thank You all for helping me.


0
//you can also try converting rgb into hex and verify...

// Color RGB   
 color = driver.findElement(By.id("xxxxx")).getCssValue("color").trim();    
 System.out.println("RGB_Color: " + color);  

 //  RGB to HEX   
 String color_hex[];  
 color_hex = color.replace("rgba(", "").split(",");       
 String actual_hex = String.format("#%02x%02x%02x", Integer.parseInt(color_hex[0].trim()), Integer.parseInt(color_hex[1].trim()), Integer.parseInt(color_hex[2].trim()));  

// further can verify with Actual hex value with Expected hex value  
Assert.assertEquals("actual_hex should equal to: ", "#808080", actual_hex);

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接