How to get the color of an element using Selenium

I want to check the color of an element in an html page. The color of this element is set using javascript, look at the imageenter image description here

An element with div-id "Ab_banco_M1T1_switch" can take 4 values, of course only one of them is displayed in accordance with the value of the variable "val". The value of the variable val is set from the server in some way, it looks like the script polls the server every X seconds and updates the value of val.

I tried to get the color of the element as follows:

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")

without success, they return "zero" or the inverse color of the page.

The only way to get color is to use 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.

.

+4
3

( ):

element.getCssValue("background-color");

/:

element.getCssValue("color");

, "" 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);
+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);

, getCssValue("color"); getCssValue("background-color");. RGB, hex. , , getCssValue.

+3

XPath . //div[@style='background: red']. , CSS getCSSValue()

0

Source: https://habr.com/ru/post/1537512/


All Articles