硒 WD / Java |无法创建 'if' & 'else if' 语句

Selenium WD / Java | Cannot create 'if' & 'else if' statement

我有一个网页,如果特定股票是 opened/closed,它会显示一个指标。 为此,我想设置一个 if & else if 语句。由于某种原因,我在 eclipse 中遇到错误。

*注意:不知道它是否有帮助,但如果我 copy/paste 代码到一个新的空 class 即 'Main' 代码,它可以正常工作没有任何错误- 所以我猜代码的结构是好的。

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;

public class TestClock {

public static void chromeMethod(WebDriver driver) {
    System.setProperty("webdriver.chrome.driver", "C:\automation\drivers\chromedriver.exe");
}

public static void runTestClock(WebDriver driver)
{


    WebElement Status = null;
    if( Status == driver.findElement(By.cssSelector(".redClockBigIcon")));
    {
        System.out.println("Stock is closed");
        driver.navigate().back();
    }

    else if (Status == driver.findElement(By.cssSelector(".greenClockBigIcon")) );
    {
        System.out.println("Stock is open");

        driver.navigate().back();
    }

}
}

我在 'else' 下遇到语法错误:

Syntax error on token "else", delete this token

else if (Status == driver.findElement(By.cssSelector(".greenClockBigIcon")) );

这是你的错误:最后一个;必须删除

您发布的代码有一些问题。

  1. 您将 ; 放在 ifelse if 语句的末尾。它们都应该被删除。

  2. 您正在将元素 Status(当前为 null)与 .findElement() return 进行比较。如果没有找到该元素,它将抛出异常,而不是 return 一个 null 元素。解决这个问题的方法是使用 .findElements()(注意复数,Elements)并检查列表是否为空。如果为空,则未找到该元素。

  3. 您的 .back() 声明在两种情况下都存在。因此,它可以移出 if 并以任何一种方式执行。

重写代码

public static void runTestClock(WebDriver driver)
{
    if (driver.findElements(By.cssSelector(".redClockBigIcon")).isEmpty())
    {
        System.out.println("Stock is closed");
    }
    else if (driver.findElements(By.cssSelector(".greenClockBigIcon")).isEmpty())
    {
        System.out.println("Stock is open");
    }
    driver.navigate().back();
}

说了这么多...通过查看您正在使用的 CSS 选择器,我猜想绿色表示股票开盘,红色表示股票收盘。这意味着你的逻辑倒退了。我认为您需要将消息切换为打开 <-> 关闭,但您会比我更清楚...

请删除; (分号)在 if 和 else if 语句的末尾。