anirudha agnihotri
anirudha agnihotri

Reputation: 65

How to get CSS colour value using Xpath?

Below is this script I tried.

  1. How can we identify the element with and get CSS color value using this XPath?
  2. What is the meaning of this Xpath?

    package mypackage;    
    import org.openqa.selenium.*;
    import org.openqa.selenium.firefox.FirefoxDriver;    
    import org.openqa.selenium.interactions.Action;
    import org.openqa.selenium.interactions.Actions;
    
    public class myclass {
    
            public static void main(String[] args) {
            String baseUrl = "http://newtours.demoaut.com/";
            WebDriver driver = new FirefoxDriver();
    
            driver.get(baseUrl);
            WebElement link_Home = driver.findElement(By.linkText("Home"));
            WebElement td_Home = driver
            .findElement(By
            .xpath("//html/body/div"
            + "/table/tbody/tr/td"
            + "/table/tbody/tr/td"
            + "/table/tbody/tr/td"
            + "/table/tbody/tr"));
    
            Actions builder = new Actions(driver);
            Action mouseOverHome = builder
            .moveToElement(link_Home)
            .build();
    
            String bgColor = td_Home.getCssValue("background-color");
            System.out.println("Before hover: " + bgColor);
            mouseOverHome.perform();
            bgColor = td_Home.getCssValue("background-color");
            System.out.println("After hover: " + bgColor);
            driver.quit();
        }
    }
    

Upvotes: 2

Views: 4785

Answers (2)

Saifur
Saifur

Reputation: 16201

First of all, this is of course not an efficient way to write xpath. I tested your xpath and it returns 9 different matches. To find css color value of a specific element your xpath or any other selector needs to be very specific. After that getCssValue and with any valid property name such as color, background-color and such will return you desire value. Your code looks fine to me except the selector. Additionally, if you want to find css values for all elements that xpath retuning you might want to loop and print the values of each. enter image description here

Upvotes: 0

Subh
Subh

Reputation: 4424

To get CSS colour value using Xpath, you can use this code:

String color = driver.findElement(By.xpath("//xpath")).getCssValue("color");

It will return output in "RGBA" format as: "rgba(255, 255, 255, 1)".

Upvotes: 1

Related Questions