如何对 WebElement 使用 if 语句

How to use if statement for a WebElement

我正在测试股票网站

我在每只股票的页面上都有一个特定的 'clock',显示该股票当前是否 open/closed 可交易

closed : class="inlineblock redClockBigIcon middle  isOpenExchBig-1"

opened : class="inlineblock greenClockBigIcon middle  isOpenExchBig-1014"

唯一的属性是 'class'。我想使用 'if' 语句以便区分它们,我尝试在 'closed' 状态下 运行 它(请参阅下面的代码 'Check',从下往上算12行)。

它在第三次循环时抛出异常:

org.openqa.selenium.NoSuchElementException: no such element

为什么?请问我该如何解决?

public static void main(String[] args) throws InterruptedException {
    System.setProperty("webdriver.chrome.driver", "C:\automation\drivers\chromedriver.exe"); 
    WebDriver driver = new ChromeDriver(); 

    driver.get("https://www.investing.com"); 
    driver.navigate().refresh();
    driver.findElement(By.cssSelector("[href = '/markets/']")).click();;


    // list |

    int size = 1;
    for (int i = 0 ; i < size ; ++i) {

        List <WebElement> list2 = driver.findElements(By.cssSelector("[nowrap='nowrap']>a"));

        //Enter the stock page
        size = list2.size();
        Thread.sleep(3000);
        list2.get(i).click();


        **//Check**
         WebElement Status = null;

         if (Status == driver.findElement(By.cssSelector("[class='inlineblock redClockBigIcon middle  isOpenExchBig-1']")))
         {
             System.out.println("Closed");
         }


        // Print instrument name
        WebElement instrumentName = driver.findElement(By.cssSelector("[class='float_lang_base_1 relativeAttr']"));
        System.out.println(instrumentName.getText());



        Thread.sleep(5000);
        driver.navigate().back();
    }
}

}

尝试使用

     WebElement Status = null;

     if (Status == driver.findElement(By.className("redClockBigIcon")))
     {
         System.out.println("Closed");
     }

你的循环没有 运行 3 次,但这不是这里的问题。

您正在使用 findElement,其中 return 是一个 WebElement,如果未找到该元素,则会引发错误。如果您在页面上不知道股票是否开盘,您有两个选择:

  1. 抓住任何 NoSuchElementExceptions。如果抛出此错误,则未找到已关闭的 class,因此页面已打开。
  2. 使用 findElements 而不是 findElement。这将 return 一个元素列表,如果 Selenium 找不到任何元素,则不会抛出异常。拿到列表后,直接查看列表中的元素个数即可。

选项 1:

boolean isClosed = false;

try {
    isClosed = driver.findElement(By.cssSelector("[class='redClockBigIcon']")).isDisplayed();
}
catch (NoSuchElementException) {
    isClosed = false;
}

选项 2:

List<WebElement> closedClockElements = driver.findElements(By.cssSelector("[class='redClockBigIcon']"));

if (closedClockElements.size() > 1) {
    System.out.println("Closed");
}
else {
    System.out.println("Open");
}