我們在做WEB自動化時,一般要等待頁面元素加載完成后,才能執行操作,否則會報找不到元素的錯誤,這樣就要求我們在有些場景下加等待時間。
SeleniumBasic有三種等待方式:
- 強制等待:與Selenium無關的一種堵塞線程的延時方法,固定毫秒數
- 隱式等待:設置一個等待時間,如果在這個等待時間內,網頁加載完成,則執行下一步;否則一直等待時間截止,然后再執行下一步。這樣也就會有個弊端,程序會一直等待整個頁面加載完成,直到超時,但有時候我需要的那個元素早就加載完成了,
- 顯式等待:程序每隔一定時間檢查一次,如果條件成立了,則執行下一步,否則繼續等待,直到超過設置的最長時間,然后拋出TimeoutException
SeleniumBasic的Utility類提供了一個Sleep方法,用於實現強制等待。
WD.New_ChromeDriver Service:=Service, Options:=Options WD.URL = "https://www.baidu.com" Dim form As SeleniumBasic.IWebElement Dim keyword As SeleniumBasic.IWebElement Dim button As SeleniumBasic.IWebElement Set form = WD.FindElementById("form") Set keyword = form.FindElementById("kw") Dim U As Utility Set U = New SeleniumBasic.Utility keyword.SendKeys "好看視頻" U.Sleep 3000 keyword.Clear
以上程序,在輸入框中鍵入“好看視頻”,過3秒后清空文本框內容。
SeleniumBasic有一個ITimeouts類,下面有3個成員,其中ImplicitWait就是隱式等待,這是一個可寫屬性。圖中把隱式等待時間設置為5秒。
顯式等待,是在查找定位某個元素之前,設置一下最大等待時間。在規定的時間內容如果找到了該元素,則提前繼續往下執行程序。如果未找到元素則出現“運行時錯誤”。
VB.NET中實現顯式等待的代碼是:
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button5.Click Dim d As IWebDriver Dim w As WebDriverWait Dim su As IWebElement d = New Chrome.ChromeDriver d.Url = "https://www.baidu.com/" w = New WebDriverWait(driver:=d, timeout:=TimeSpan.FromSeconds(4)) su = w.Until(Function(x As IWebDriver) x.FindElement(By.Id("su"))) su.Click() d.Quit() Exit Sub End Sub
由於VBA語言中使用New關鍵字創建類實例時不許傳遞參數。因此在SeleniumBasic中,Set WDW =New WebDriverWait這句沒有實際效果,必須調用自定義方法Create讓該對象與IWebDriver關聯。
下面的代碼首先打開百度首頁,然后設置一個顯式等待對象WDW,等待時間是5秒鍾。然后調用Until方法查找ID為su的元素。
Private WD As SeleniumBasic.IWebDriver Sub Baidu() On Error GoTo Err1 Set WD = New SeleniumBasic.IWebDriver WD.New_ChromeDriver WD.URL = "https://www.baidu.com" Dim button As SeleniumBasic.IWebElement Dim WDW As WebDriverWait Set WDW = New WebDriverWait WDW.Create driver:=WD, timeout:=5 Set button = WDW.Until(attributeName:="Id", attributeValue:="su") If button Is Nothing = False Then MsgBox button.GetAttribute("value"), vbInformation End If Debug.Print WD.Title, WD.URL WD.Quit Exit Sub Err1: MsgBox Err.Description, vbCritical WD.Quit End Sub
如果定位到了,在VBA中返回該元素的value屬性“百度一下”
假設,故意把Id寫錯:
再次執行上述代碼,由於不存在該元素,進入“運行時錯誤”