如何使用Python处理Selenium中的JavaScript警告提示框

6

我想要点击一个按钮,如果这是你第一次点击它,会弹出一个JavaScript警告框。我一直在使用Firebug,但找不到JavaScript代码所在的位置,我已经尝试过。

if EC.alert_is_present:
        driver.switch_to_alert().accept()
else:
    print("no alert")

如果有弹出框,上述代码可以正常工作,但如果没有弹出框,则会抛出错误。尽管有else语句,我甚至尝试过

   if EC.alert_is_present:
            driver.switch_to_alert().accept()
   elif not EC.alert_is_present:
               print("no alert")

我遇到了这个错误

selenium.common.exceptions.NoAlertPresentException: Message: No alert is present

我们应该怎样解决这个问题?

这可能是根本原因吗?绕过 fxdriver.modals.clearFlag_ 的调用...参见 https://stackoverflow.com/questions/44568402/how-do-i-manually-mouse-dismiss-a-javascript-alert-and-get-back-the-the-body-o/44592827#44592827 - NevilleDNZ
2个回答

8

使用try catch语句,如果弹出框不存在,则捕获NoAlertPresentException异常:

from selenium.common.exceptions import NoAlertPresentException

try:
    driver.switch_to_alert().accept()
except NoAlertPresentException as e: 
    print("no alert")

名称“ NoAlertPresentException”未定义。这是输出结果。我们如何定义它? - Halcyon Abraham Ramirez
请使用 selenium.common.exceptions.NoAlertPresentException 代替 NoAlertPresentException - Saifur
在处理上述异常时,又发生了另一个异常:Traceback (most recent call last): File "C:\Python34\test.py", line 1995, in <module> except (NoAlertPresentException) as e: NameError: name 'NoAlertPresentException' is not defined - Halcyon Abraham Ramirez
仍然无法工作。我将包含所有的错误信息。 - Halcyon Abraham Ramirez
导入 from selenium.common.exceptions import NoAlertPresentException 怎么样? - Saifur
显示剩余2条评论

4
这是实现方法:
from selenium.common.exceptions import NoAlertPresentException
try:
    context.driver.switch_to.alert.accept()
except NoAlertPresentException:
    pass

如果您希望,可以用print语句替换pass。请注意使用switch_to.alert而不是switch_to_alert()。后者已经过时了。在我这里的Selenium版本中,我看到它的代码:

warnings.warn("use driver.switch_to.alert instead", DeprecationWarning)

我可以知道为什么我们不应该使用 switch_to_alert() 吗? - Nam G VU

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接