在做UI自動化的時候,很多時候我們會遇到各種錯誤信息,比如頁面元素找不到(Caused by: org.openqa.selenium.NoSuchElementException: Unable to locate element:),這個在做自動化的時候是比較常見的問題。那麼一般導致找不到元素的原因最多的就是等待時間,很多時候是頁面還未加載完成或者元素出現的時間有延遲,所以設置等待時間。
現在的網頁中很多是交互的,你要尋找元素的時候,有可能是基於上面的步驟操作,纔出現這個元素,而且由於網絡的原因,元素加載可能需要一定的時間,所以這裏一定要在查找元素的時候使用等待。
WebDriver中提供了三種等待方式:
1.*implicitlyWait():隱式等待,查找元素的時候一直找,直到超過設置的最大等待時間,會拋出沒有找到元素的異常
package com.yumeihu.D1;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
public class WaitThree {
public static void main(String[] args) throws Exception {
WebDriver driver = new FirefoxDriver();
driver.manage().window().maximize();
/*
#等待頁面元素加載
#其實大多數情況下定位不到元素就是兩種問題:1 有frame,2 沒有加等待。
*/
driver.get("http://www.baidu.com");
driver.manage().timeouts().implicitlyWait(1, TimeUnit.SECONDS);
driver.findElement(By.id("kw")).sendKeys("you are so beautiful");
driver.findElement(By.id("su")).click();
2.pageLoadTimeout();
比如我們訪問一個外國網站的話,速度會很慢,這個時候我們要等頁面元素全部加載完成,纔可以進行下一步操作,在設定的時間內頁面未加載完成,此時就會報錯。
package com.yumeihu.D1;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
public class PageLoadTimeOuter{
public static void main(String[] args) throws Exception {
WebDriver driver = new FirefoxDriver();
//瀏覽器最大化
driver.manage().window().maximize();
//*pageLoadTimeout() 在設置的時間內等待網頁加載完成,如果超時,則拋出異常
driver.manage().timeouts().pageLoadTimeout(1,TimeUnit.SECONDS);
driver.get("https://www.earthtv.com/en");
System.out.println("已經成功進入:"+ driver.getTitle());
這裏我們設置了一秒的等待時間,在一秒的時間內,該網頁未加載完成,所以,控制檯會輸出頁面加載超時的錯誤,所以,我們合理的利用這些等待時間,在合適的位置,就可以知道爲什麼元素定位不到,很快的找到解決辦法。。。。。。。。。。。
3.Thread.sleep();
強制等待,將當前線程掛起指定的時間。()括號中的時間是毫秒;比如Thread.sleep(3000);指的是等待3秒。
package com.yumeihu.D1;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
public class PageLoadTimeOuter{
public static void main(String[] args) throws Exception {
WebDriver driver = new FirefoxDriver();
//瀏覽器最大化
driver.manage().window().maximize();
String url = "http://www.baidu.com";
driver.get(url+"/");
driver.findElement(By.id("kw")).sendKeys("Lion is so beautiful");
//等待2秒後再執行點擊
Thread.sleep(2000);
driver.findElement(By.id("su")).click();
so~SO~
好了,這次的等待時間就說到這裏