如何在 Selenium WebDriver 中使用 Javascript 获取元素的背景颜色

How to get the background-color of an element using Javascript in Selenium WebDriver

我想获取滚动元素的背景颜色。 https://www.ndtv.com/business 在这个网站中,我想获得 GOLD 的背景颜色,无论是红色还是蓝色... 有时我可以找到该元素,例如,当它在网络上可用时..其他时候它 returned 为找不到元素... 我怎么能确定,我一定会得到它.. 这是代码。

[![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]

我在您的代码中看到的唯一问题是您编写了很多乱七八糟的 xpath。您使用了不必要的转义字符 (\),这使您的 xPath 很难分析。我已经采取了其中一个块来演示。您可以对所有元素使用相同的元素。

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

输出:

注意:另外不要在脚本中同时使用隐式等待和显式等待。它会使您的脚本不可预测,甚至在不需要时也可能导致长时间延迟。