selenium-03-02操作元素-等待

1、最直接普通的方式:这个是设置固定的等待时间

   Thread.sleep(1000);  
2、隐式等待方式(implicitlyWait):设置脚本在查找元素时的最大等待时间;
   driver.manage().timeouts().implicitlyWait(second, TimeUnit.SECONDS);    
代码示例如下:
    public boolean isByElementDisplayed(By by, int time,WebDriver chrome) {
        boolean status = true;
        while(!isByPresent(chrome, by)){
            chrome.manage().timeouts().implicitlyWait(15, TimeUnit.SECONDS);
        }
        return status;      
    }
    
    public boolean isByPresent(WebDriver chrome, By by){
        boolean display = false;
        try{
            chrome.findElement(by).isDisplayed();
            return display= true;
        }catch(NoSuchElementException e){
            return display;
        }
    }  
这里用while循环是如果明确需要查找的元素未找到,就继续循环等待;
3、显示等待方式(Explicit Wait):就是明确的要等待的元素在规定的时间之内都没找到,那么就抛出Exception.代码示例如下:

new WebDriverWait(chrome, 15).until(

ExpectedConditions.presenceOfElementLocated(By.cssSelector("css locator"))

);    
这里,15是要等待的秒数.如果没有满足until()方法中的条件,就会始终在这里wait 15秒,依然找不到,就抛出异常 。

还可以这样写:

    WebDriver chrome= new ChromeDriver() ;
    chrome.get( http://somedomain/url_that_delays_loading);
    WebElement e = (new WebDriverWait( chrome, 10)) .until(
        new ExpectedCondition< WebElement>(){
            @Override  //方法重写
            public WebElement ByPresent( WebDriver d) {
                return d.findElement( By.id("id locator"));
            }
        }
    );   
这样就通过回调函数,直接获得了这个WebElement.也就是页面元素 。
原文地址:https://www.cnblogs.com/i16i1007/p/6626814.html