【问题标题】:How to use if statement for a WebElement如何为 WebElement 使用 if 语句
【发布时间】:2017-12-03 14:14:49
【问题描述】:

我正在测试一个股票网站

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

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

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

唯一的属性是“类”。我想使用“if”语句以便区分它们,我尝试在“关闭”状态下运行它(请参阅下面的代码'Check',距底部 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();
    }
}

}

【问题讨论】:

  • 你能把你的html粘贴到这里吗?

标签: if-statement selenium-webdriver qwebelement


【解决方案1】:

尝试使用

     WebElement Status = null;

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

【讨论】:

    【解决方案2】:

    您的循环没有运行 3 次,但这不是问题所在。

    您正在使用findElement,它返回一个 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");
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-08-04
      • 1970-01-01
      • 2014-06-12
      • 1970-01-01
      • 1970-01-01
      • 2020-03-16
      • 2017-08-30
      • 1970-01-01
      相关资源
      最近更新 更多