Wait for an element using Selenium webdriver

后端 未结 4 657
耶瑟儿~
耶瑟儿~ 2021-01-23 07:11

What is the best way to wait for an element to appear on a web page? I have read that we can use implicit wait and functions like webdriverwait, fluentwait etc and last but not

相关标签:
4条回答
  • 2021-01-23 07:31

    Always start by using a implicit wait. I think Selenium defaults to 5 seconds and so if you do a driver.findElement(), the implication is that it will wait up to 5 seconds. That should do it. If you are experiencing a scenario where the time it takes is unpredictable, then use FluentWait (with the same 5 second timeout) but also using the .ignoring method and wrap that inside a while loop . Here is the basic idea:

    int tries=0;
    while ( tries < 3 ) {
      //fluent wait (with .ignoring) inside here
      tries ++1;
    }
    
    0 讨论(0)
  • 2021-01-23 07:33

    You could wait for the presence of the element to appear as follows:

    new WebDriverWait(driver, 10).until(ExpectedConditions.presenceOfElementLocated(By.id("someId")));
    
    0 讨论(0)
  • 2021-01-23 07:37
    WebDriverWait wait = new WebDriverWait(driver, 20);
    wait.until(ExpectedConditions.elementToBeClickable(By.id("optionsBuilderSelect_input")));
    

    I'm a professional scraper (http://nitinsurana.com) I've written 30+ softwares using selenium and I've never faced any such issue, anyways above is a sample code.

    All I can think of is that what until condition has to be checked because many a times elements are already visible, but they are not clickable and things like that. I guess you should give different options a try and I hope you'll find the one required.

    0 讨论(0)
  • 2021-01-23 07:51
    public boolean waitForElement(WebElement ele, String xpath, int seconds) throws InterruptedException{
        //returns true if the xpath appears in the webElement within the time
        //false when timed out
        int t=0;
        while(t<seconds*10){
            if(ele.findElements(By.xpath(xpath)).size()>0)
                return true;
            else{
                Thread.sleep(100);
                t++;
                continue;
            }
        }       
        System.out.println("waited for "+seconds+"seconds. But couldn't find "+xpath+ " in the element specified");
        return false;
    }
    
    0 讨论(0)
提交回复
热议问题