0

我正在测试一个股票网站

我在每只股票的页面上都有一个特定的“时钟”,显示股票当前是否开盘/收盘进行交易

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

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

唯一的属性是“类”。我想使用“if”语句以便区分它们,我尝试在“关闭”状态下运行它(请参阅下面的“检查”代码,从底部开始 12 行)。

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

org.openqa.selenium.NoSuchElementException:没有这样的元素

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

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

}

4

2 回答 2

0

您的循环不会运行 3 次,但这不是这里的问题。

您正在使用findElementwhich 返回 WebElement 或在未找到该元素时引发错误。如果您在一个页面上并且您不知道股票是否开盘,您有两种选择:

  1. 抓住任何NoSuchElementExceptions. 如果抛出此错误,则找不到已关闭的类,因此页面已打开。
  2. 使用findElements而不是findElement. 这将返回一个元素列表,如果 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");
}
于 2017-12-03T22:42:21.703 回答
0

尝试使用

     WebElement Status = null;

     if (Status == driver.findElement(By.className("redClockBigIcon")))
     {
         System.out.println("Closed");
     }
于 2017-12-03T16:15:07.787 回答