1

I want to get the background color of an element which is scrolling. https://www.ndtv.com/business in this website, i want to get the background color of GOLD whether its red or Blue... Sometime i can find the element , like, when its available in the web..other times it returned as element not found... How can i make sure, i will get it for sure.. Here is the code..I used wait, and Javascript..both return the same error...

[![import org.testng.annotations.Test;

import junit.framework.Assert;

import org.testng.annotations.BeforeTest;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.TimeUnit;

import org.openqa.selenium.By;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;
import org.openqa.selenium.interactions.Actions;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
import org.testng.annotations.AfterTest;

public class Question3 {
    WebDriver driver ;
    WebDriverWait wait;
    @BeforeTest
      public void beforeTest() {
        System.setProperty("webdriver.chrome.driver", "src\\test\\resources\\drivers\\chromedriver.exe");
          ChromeOptions options = new ChromeOptions();
         
          options.setExperimentalOption("excludeSwitches", Arrays.asList("disable-popup-blocking"));

          options.addArguments("--disable-popup-blocking");

          driver = new ChromeDriver(options);
          driver.manage().window().maximize();
          driver.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS);
        driver.get("https://www.ndtv.com/business ");
        System.out.println("******* Execution Started **********");
      }
    @Test
  public void test() throws InterruptedException {
        driver.switchTo().frame(1);
        JavascriptExecutor js = (JavascriptExecutor)driver;
         wait = new WebDriverWait(driver,90);
        Actions action = new Actions(driver);
        String filename = "src\\test\\resources\\screenshots\\Question3.png";

        wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//*\[@id=\"header-data\"\]/a\[6\]/span/span\[1\]")));
        try {
        String Gold_old = driver.findElement(By.xpath("//*\[@id=\"header-data\"\]/a\[6\]/span/span\[1\]")).getAttribute("innerText");
        System.out.println("Gold old : "+ Gold_old);
        
        String Gold_new = driver.findElement(By.xpath("//*\[@id=\"header-data\"\]/a\[6\]/span/span\[2\]/span")).getAttribute("innerText");
        System.out.println("Gold New : "+ Gold_new);
        
        String Variation = driver.findElement(By.xpath("//*\[@id=\"header-data\"\]/a\[6\]/span/span\[2\]")).getAttribute("innerText");
        String Var_Value = Variation.substring(8, 14);
        System.out.println("Gold variation : "+ Var_Value);
        }catch(Exception e) {
            System.out.println("Running from Exception..." + e.getMessage());
            String Gold_old = driver.findElement(By.xpath("//*\[@id=\"header-data\"\]/a\[6\]/span/span\[1\]")).getAttribute("innerText");
            System.out.println("Gold old : "+ Gold_old);
            
            String Gold_new = driver.findElement(By.xpath("//*\[@id=\"header-data\"\]/a\[6\]/span/span\[2\]/span")).getAttribute("innerText");
            System.out.println("Gold New : "+ Gold_new);
            
            String Variation = driver.findElement(By.xpath("//*\[@id=\"header-data\"\]/a\[6\]/span/span\[2\]")).getAttribute("innerText");
            String Var_Value = Variation.substring(8, 14);
            System.out.println("Gold variation : "+ Var_Value);
        }
        
        //wait.until(ExpectedConditions.elementToBeClickable(By.xpath("(//*\[@id=\"header-data\"\]/a\[8\]/span/span\[2\]")));
        String sText =  js.executeScript("return document.driver.findElement(By.xpath(\"//*\[@id=\"header-data\"\]/a\[8\]/span/span\[2\]\")).style.background-color;").toString();
        System.out.println(sText);
        
        String Background = driver.findElement(By.xpath("(//*\[@id=\"header-data\"\]/a\[8\]/span/span\[2\]")).getCssValue("background-color");
        System.out.println("Background color is : "+ Background);
        String BG_RGB = Background.replace("rgba(", "rgb(");
        String RGB = BG_RGB.substring(0, 14) + ")" ;
        String RGB_Value = RGB.substring(3);
        System.out.println("Background color in RGB is : "+ RGB );
        System.out.println(" RGB value is : "+ RGB_Value);
        Assert.assertEquals("(12, 162, 2)", RGB_Value);
        
        Thread.sleep(1000);
        wait.until(ExpectedConditions.stalenessOf(driver.findElement(By.xpath("/html/body/div/header/header/div/div\[1\]/div\[2\]/div/div/div/div/a\[4\]"))));
        
        //driver.findElement(By.xpath("/html/body/div/header/header/div/div\[1\]/div\[2\]/div/div/div/div/a\[4\]")).click();
        js.executeScript("argument\[0\].click();",driver.findElement(By.xpath("/html/body/div/header/header/div/div\[1\]/div\[2\]/div/div/div/div/a\[4\]")) );
        
        wait.until(ExpectedConditions.visibilityOf(driver.findElement(By.xpath("//a\[@id=\"By Gain\"\]"))));
        action.moveToElement(driver.findElement(By.xpath("//a\[@id=\"By Gain\"\]"))).perform();
        js.executeScript("argument\[0\].click();",driver.findElement(By.xpath("//a\[@id=\"By Gain\"\]")));
                
        Thread.sleep(1000);
        System.out.println("********** Clicked Gain *********");
        
        //JavascriptExecutor js = (JavascriptExecutor) driver;
        //js.executeScript("arguments\[0\].scrollIntoView();", driver.findElement(By.xpath("//a\[@id=\"By Gain\"\]")));
        //js.executeScript("window.scrollBy(0,document.body.scrollHeight)");
        Thread.sleep(1000);
        WebElement firstchoice = driver.findElement(By.xpath("//*\[@id=\"peerlist1\"\]/li\[1\]"));
        
        
        action.moveToElement(firstchoice).perform();
        
        utils.HelperFunctions.captureScreenShot(driver, filename);
        Thread.sleep(1000);
        
        String cellvalue = driver.findElement(By.xpath("//*\[@id=\"peerlist1\"\]/li\[1\]/a/span")).getText();
        
        System.out.println("Hover Text is " + cellvalue);
        
        String CellRGB = driver.findElement(By.xpath("//*\[@id=\"peerlist1\"\]/li\[1\]")).getCssValue("background-color");
        System.out.println("Cell's RGB value is " + CellRGB);
        try {
        String celltext = driver.findElement(By.xpath("//*\[@id=\"peerlist1\"\]/li\[1\]/a")).getAttribute("innerText");
        System.out.println("Cell's text is " + celltext);
        }catch(Exception e) {
            String celltext = driver.findElement(By.xpath("//*\[@id=\"peerlist1\"\]/li\[1\]/a")).getText();
            System.out.println("Cell's text is " + celltext);
        }
        List<WebElement> row_data = driver.findElements(By.xpath("//*\[@id=\"peerlist1\"\]/li\[*\]"));
        int i = 0;
        ArrayList<String> obtainedList = new ArrayList<>(); 
        for(WebElement li : row_data) {
            if(i>=6) {
                break;
            }else {
                
            
            String text = li.getText();
            obtainedList.add(text);
            i++;
            }
        }
        System.out.println("Original List " + obtainedList);
        ArrayList<String> sortedList = new ArrayList<>(); 
        for(String s:obtainedList){
            sortedList.add(s);
            }
            Collections.sort(sortedList);
            System.out.println("Sorted List " + sortedList);
            Assert.assertTrue(sortedList.equals(obtainedList));
        
        
    
  }
  

  @AfterTest
  public void afterTest() {
      System.out.println("******* Execution end **********");
    driver.quit();
      
  }

}][1]][1]
3
  • Sorry the color should be RED or GREEN Commented Sep 4, 2020 at 12:29
  • Can you clarify what help you need? - Are after making sure your object is available every time? or getting the background colour as the title says? -- your code already seems to do work after gettting the colour - but i can see your xpaths need work and that might help with object identification ... Dropping in >100 lines of code isn't the best appraoch - Do you think you please refer to the "How to ask" and create an MRE: stackoverflow.com/help/minimal-reproducible-example Commented Sep 4, 2020 at 13:08
  • Okay thanks @RichEdwards ...I want to get the background color...//wait.until(ExpectedConditions.elementToBeClickable(By.xpath("(//*[@id=\"header-data\"]/a[8]/span/span[2]"))); String sText = js.executeScript("return document.driver.findElement(By.xpath(\"//*[@id=\"header-data\"]/a[8]/span/span[2]\")).style.background-color;").toString(); System.out.println(sText); String Background = driver.findElement(By.xpath("(//*[@id=\"header-data\"]/a[8]/span/span[2]")).getCssValue("background-color"); These lines throws error Commented Sep 4, 2020 at 16:15

1 Answer 1

2

The only issue i can see with your code is that you have written a lot of messed xpaths. You have used escape character (\) unnecessary, which has make your xPath very difficult to analyse. I have taken one of the block to demonstrate. You can use same for all elements.

WebDriver  driver = new ChromeDriver();
WebDriverWait wait = new WebDriverWait(driver,60);
driver.manage().window().maximize();
driver.get("https://www.ndtv.com/business");
driver.switchTo().frame(1);
WebElement ele = wait.until(ExpectedConditions.presenceOfElementLocated(By.xpath("//*[@id='header-data']/a[8]/span/span[2]")));

String Background = ele.getCssValue("background-color");
System.out.println("RGB : "+ Background);

//In case you want hex value of color code
String hex = Color.fromString(Background).asHex();
System.out.println(hex); 

output:

enter image description here

Note : Also do not use combination of both implicit wait and explicit wait in your script. It will make your script unpredictable and can cause long delays even when not needed.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.