javaseleniumselenium-chromedrivernosuchelementexceptionfindelement

I'm trying to Check if a certain WebElement is present through chrome drive in java after checking the page is loaded, but it's not working


I'm trying to Check if a certain WebElement is present through chrome drive in java after checking the page is loaded. even though the page is loaded and the element is present the driver can't locate it and I get a NoSuchElementException. if I'll let it run more time it would probably make it but that's not possible with logic of my code because I'm checking if this element is present while the page is loaded to see if something is clickable (when I over it looks clickable but when I click it nothing happen so something like "isClickable" {if that's a thing} probably won't work) and gets me to the right place.

part of my code:

while (true) {
                    JavascriptExecutor js = (JavascriptExecutor) driver;
                    if (js.executeScript("return document.readyState").toString().equals("complete")) {
                        try {
                            if (driver.findElement(By.xpath("/html/body/div[1]/div/div[4]/div/div/div/div/div[1]/div")).isEnabled()) {
                                inProfilePictureTab = true;
                                toBreak = true;
                                break;
                            }
                        } catch (NoSuchElementException exception) {
                            warningLabelChanger("Profile picture isn't clickable, try something else");
                            toBreak = true;
                            break;


                        } catch (NullPointerException exception2) {

                        }
                    }
                    try {
                        Thread.sleep(Constants.SLEEP_TIME);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }

How can I fix that?


Solution

  • The solution discussed in the comments was to add a wait.

    Add this once when you create the driver object:

    driver.manage().timeouts().implicitlyWait(10,TimeUnit.SECONDS)