1. 程式人生 > >selenium 延遲等待的三種方式

selenium 延遲等待的三種方式

 1、最直接普通的方式:這個是設定固定的等待時間    Thread.sleep(1000);
2、隱式等待方式(implicitlyWait):設定指令碼在查詢元素時的最大等待時間;    driver.manage().timeouts().implicitlyWait(second, TimeUnit.SECONDS);    
程式碼示例如下     public boolean isByElementDisplayed(By byint 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
 displaytrue;
        }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 chromenew 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.也就是頁面元素 。