VBA Selenium Chrome意外警报错误

时间:2020-07-14 17:43:02

标签: excel vba selenium-chromedriver

我目前正在使用Selenium,VBA Excel和Chrome浏览器从网站上抓取信息。一切正常,直到网站上没有列表中的值之一,然后出现运行时错误'26'UnexpectedAlertOpenError Error image

我已添加此行 Chrome.SwitchToAlert(5).accept 来处理错误,该错误在值不可用时有效。不幸的是,当列表中的值可用时,添加该行将返回运行时错误'27'NoAlertPresentError Error image

错误消息很有意义,不能对不存在的内容采取行动。我需要一种方法来检查是否有警报,如果有,则退出chrome,否则运行其余代码。我尝试了id name ... 123 City A 456 City B 789 City C 789 City C 456 City B 123 City A . . . If Chrome.FindElementsByTag("tr") Is Nothing Then Chrome.SwitchToAlert(5).accept else 等操作,但是似乎无法解决错误26。

1 个答案:

答案 0 :(得分:0)

好吧,基于 VBA selenium 库,我显然无法检查已显示的警报计数,我们可以使用以下方法对浏览器窗口执行以下操作:

driver.Windows.Count 'driver being the variable used to refer to an instance of Chromedriver

所以我使用的解决方案是在错误处理程序之间包装整个 selenium 代码:​​

On Error Goto Problem:
' Your code over here
''''''
''''''
On Error Goto 0

Exit Sub
Problem:
    If InStr(1, Err.Description, "Alert") <> 0 Then
        driver.SwitchToAlert.accept 'could also use: driver.SwitchToAlert.dismiss
        Resume Next 'resumes code from the next line in code that threw error
    End If

这样我相信每当突然出现意外警报时,错误处理程序都会接受/解除警报,并通过“继续下一步”确保程序从下一行继续