Selenium Webdriver (VBA):显式等待

ex-*_*pat 4 excel selenium vba webdriver

我正在浏览一个 Web 应用程序,如果在与元素交互之前尝试单击该元素,该应用程序通常会引发错误。

使用 Selenium WebDriver (java) 时,我可以轻松解决这个问题:

 WebDriverWait wait = new WebDriverWait(driver, 15);

 wait.until(ExpectedConditions.elementToBeClickable(By.id("element")));
Run Code Online (Sandbox Code Playgroud)

但是,我正在尝试使用 Selenium 类型库在 VBA 中编写脚本,尽管尝试了多种不同的方法,但我获得的唯一成功是:

webdriver.wait
Run Code Online (Sandbox Code Playgroud)

我被告知应该尽可能避免。如果有人可以建议如何将我的 java 转换为 VBA,或提供任何其他解决方案,我将不胜感激。

QHa*_*arr 6

您可以尝试循环直到元素被正确设置并超时以确保您不会进入无限循环。接受的答案的危险在于,如果找不到,则无法逃脱循环。

Dim t As Date, ele As Object
t = Timer
Do
    DoEvents
    On Error Resume Next
    Set ele = .FindElementById("element")
    On Error GoTo 0
    If Timer - t = 10 Then Exit Do '<==To avoid infinite loop
Loop While ele Is Nothing
Run Code Online (Sandbox Code Playgroud)

注意:用户@florentbr 编写了一个 js 等待可点击函数以通过 Selenium Basic 执行。此SO 答案中的示例。


Tom*_*iri 2

VBA 的 selenium 插件是非官方的,不支持此功能。

您可以通过使用 onError 重试产生错误的操作来解决此问题,直到成功或超时:

Sub test
    OnError GoTo Retry
        webDriver.findElementById("element")
    Exit Sub

    Dim i as integer
    :Retry
        webDriver.Wait(500)
        i = i + 1
        if i = 20 then onerror go to 0
    Resume
end sub
Run Code Online (Sandbox Code Playgroud)