Search code examples
if-statementselenium-webdriverqwebelement

How to use if statement for a WebElement


I'm testing a website of Stocks

I have a certain 'clock' in each stock's page that shows if the stock is currently open/closed for trading

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

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

The only attribute there is a 'class'. I want to use an 'if' statement so I could distinguished between them, I tried to run it on a 'closed' status (see the code below on 'Check', 12 lines from the bottom).

It throws an exception on the third time of the loop :

org.openqa.selenium.NoSuchElementException: no such element

Why? and please how can I fix it?

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

}


Solution

  • Try using

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