如何使用Selenium获取元素颜色

use*_*132 5 html css java selenium selenium-webdriver

我想检查html页面中元素的颜色.使用javascript设置此元素的颜色,查看图像在此输入图像描述

具有div-id"Ab_banco_M1T1_switch"的元素可以假设4个值,当然根据"val"变量的值仅显示其中一个值.val变量是以某种方式从服务器设置的,它表示脚本每隔X秒轮询一次服务器并更新val的值.

我试图获得元素的颜色如下:

WebElement element = wait.until(ExpectedConditions.presenceOfElementLocated(By.id("Ab_banco_M1T1_switch")));

element.getAttribute("background")
element.getAttribute("style")
element.getAttribute("background-color") 
element.getCssValue("style")
element.getCssValue("color")
Run Code Online (Sandbox Code Playgroud)

没有成功,它们返回"null"或页面的backgorund颜色.

获得颜色的唯一方法是使用Xpath /html/body/div/div[2]/div[2]/div[2]/div/div/div/div[3]/div (for red, if I want the green /html/body/div/div[2]/div[2]/div[2]/div/div/div/div[2]/div)

但这不是我想要的.实际上,Xpath会对元素进行本地化,但它不会告诉我显示的颜色是红色还是其他颜色,我只能通过查看网页来了解它.

换句话说,我想像Firebug那样访问当前显示的颜色,看看右侧的面板,你可以看到element.style ->background-Color = red.

当我调用元素时,getCssCValue("background-color")我得到了backgorund颜色#body_right_div.

先感谢您.

Rip*_*sim 9

您可以通过以下方式获取元素颜色(元素的背景颜色):

element.getCssValue("background-color");
Run Code Online (Sandbox Code Playgroud)

您可以通过以下方式获取元素文本/标题颜色:

element.getCssValue("color");
Run Code Online (Sandbox Code Playgroud)

例如,如果您想获取LinkedIn的"登录"按钮的背景和文本颜色,则代码如下:

driver.get("https://www.linkedin.com/");
        String buttonColor = driver.findElement(By.name("submit")).getCssValue("background-color");
        String buttonTextColor = driver.findElement(By.name("submit")).getCssValue("color");
        System.out.println("Button color: " + buttonColor);
        System.out.println("Text color " + buttonTextColor);
Run Code Online (Sandbox Code Playgroud)

  • 上面的代码将返回rgb值.如果要转换为十六进制,可以访问http://stackoverflow.com/questions/19668893/getcssvalue-color-in-hex-format-in-selenium-webdriver (2认同)

小智 5

试试这个,对我来说很完美:

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);
Run Code Online (Sandbox Code Playgroud)

因此,您可以使用getCssValue("color");和 获得颜色getCssValue("background-color");。但是,这将是RGB,因此您需要转换为十六进制。然后,您可以使用十六进制代码比较该值并将其打印出来,以便查看每个值之后的结果getCssValue


oly*_*lyv 0

使用 XPath,您可以尝试按属性进行搜索。例如//div[@style='background: red']。如果你想获得颜色,那么对于CSS我会使用方法getCSSValue()