【问题标题】:how to handle javascript alerts in selenium using python如何使用 python 处理 selenium 中的 javascript 警报
【发布时间】:2015-05-09 23:50:03
【问题描述】:

所以我想点击这个按钮,如果这是您第一次点击它。将出现一个 javascript 警报弹出窗口。我一直在使用萤火虫,只是找不到那个 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

我们如何解决这个问题?

【问题讨论】:

标签: python selenium


【解决方案1】:

使用 try catch 并且如果 Alert 不存在 catch NoAlertPresentException 异常:

from selenium.common.exceptions import NoAlertPresentException

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

【讨论】:

  • 名称“NoAlertPresentException”未定义。这是输出。我们如何定义它?
  • 什么是堆栈跟踪?
  • 试试selenium.common.exceptions.NoAlertPresentException而不是NoAlertPresentException
  • 在处理上述异常期间,发生了另一个异常:Traceback(最近一次调用最后一次):文件“C:\Python34\test.py”,第 1995 行,在 中除外 (NoAlertPresentException) as e: NameError: name 'NoAlertPresentException' is not defined
  • 还是不行。我将包含所有错误消息
【解决方案2】:

这就是你的做法:

from selenium.common.exceptions import NoAlertPresentException
try:
    context.driver.switch_to.alert.accept()
except NoAlertPresentException:
    pass

如果您愿意,可以将 pass 替换为 print 语句。注意使用switch_to.alert 而不是switch_to_alert()。后者已被弃用一段时间。在我这里的 Selenium 版本中,我在其代码中看到了这一点:

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

【讨论】:

  • 我可以知道为什么我们不应该使用switch_to_alert() 吗?
猜你喜欢
  • 2022-09-23
  • 2021-11-15
  • 1970-01-01
  • 2018-12-21
  • 1970-01-01
  • 2023-01-02
  • 1970-01-01
  • 2015-03-06
  • 2012-07-25
相关资源
最近更新 更多