java selenium (十三) 智能等待頁面加載完成

咱們常常會碰到用selenium操做頁面上某個元素的時候, 須要等待頁面加載完成後, 才能操做。  不然頁面上的元素不存在,會拋出異常。  css

或者碰到AJAX異步加載,咱們須要等待元素加載完成後, 才能操做 html

selenium 中提供了很是簡單,智能的方法,來判斷元素是否存在.java

 

閱讀目錄app

實例要求 

實例:set_timeout.html 下面的html 代碼,  點擊click 按鈕5秒後, 頁面上會出現一個紅色的div快, 咱們須要寫一段自動化腳本智能的去判斷這個div是否存在, 而後把這個div 而後高亮。異步

 

<html>
    <head>
        <title>Set Timeout</title>
        <style>
            .red_box {background-color: red; width = 20%; height: 100px; border: none;}
        </style>
        <script>
            function show_div(){
                setTimeout("create_div()", 5000);
            }
  
            function create_div(){
                d = document.createElement('div');
                d.className = "red_box";
                document.body.appendChild(d);
            }
        </script>
    </head>
    <body>
        <button id = "b" onclick = "show_div()">click</button>
    </body>
</html>

 

隱式等待

        WebDriver driver = new FirefoxDriver();
        driver.get("file:///C:/Users/Tank/Desktop/set_timeout.html");    
        
        driver.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS);
        WebElement element = driver.findElement(By.cssSelector(".red_box"));      
        ((JavascriptExecutor)driver).executeScript("arguments[0].style.border = \"5px solid yellow\"",element);  

其中測試

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

意思是, 總共等待10秒, 若是10秒後,元素還不存在,就會拋出異常  org.openqa.selenium.NoSuchElementExceptionspa

 

顯式等待

顯式等待 使用ExpectedConditions類中自帶方法, 能夠進行顯試等待的判斷。 code

顯式等待能夠自定義等待的條件,用於更加複雜的頁面等待條件htm

 

等待的條件blog

WebDriver方法

頁面元素是否在頁面上可用和可被單擊

elementToBeClickable(By locator)

頁面元素處於被選中狀態

elementToBeSelected(WebElement element)

頁面元素在頁面中存在

presenceOfElementLocated(By locator)

在頁面元素中是否包含特定的文本

textToBePresentInElement(By locator)

頁面元素值

textToBePresentInElementValue(By locator, java.lang.String text)

標題 (title)

titleContains(java.lang.String title)

 

 

 

 

 

 

 

 

 

 

 

只有知足顯式等待的條件知足,測試代碼纔會繼續向後執行後續的測試邏輯

若是超過設定的最大顯式等待時間閾值, 這測試程序會拋出異常。 

 

    public static void testWait2(WebDriver driver)
    {
        driver.get("E:\\StashFolder\\huoli_28@hotmail.com\\Stash\\Tank-MoneyProject\\浦東軟件園培訓中心\\個人教材\\Selenium Webdriver\\set_timeout.html");    
        
        WebDriverWait wait = new WebDriverWait(driver, 20);
        wait.until(ExpectedConditions.presenceOfElementLocated(By.cssSelector(".red_box")));
        WebElement element = driver.findElement(By.cssSelector(".red_box"));      
        ((JavascriptExecutor)driver).executeScript("arguments[0].style.border = \"5px solid yellow\"",element);  
    }
相關文章
相關標籤/搜索