【问题标题】:Python Selenium UnexpectedAlertPresentExceptionPython Selenium UnexpectedAlertPresentException
【发布时间】:2015-04-08 11:03:15
【问题描述】:

我正在使用 selenium webdriver 使用 python 和 lettuce 运行基本的 CRUD 测试。

我的所有其他测试都运行良好,但是当我单击“删除”时,会出现一个模式对话框,要求用户确认他们是否要删除该用户。弹出窗口出现的那一刻,我得到下面的异常。我浪费了 2 个小时试图让它工作。我想有一个简单的解决方法。

 File "/usr/local/lib/python2.7/dist-packages/selenium/webdriver/remote/errorhandler.py", line 164, in check_response
    raise exception_class(message, screen, stacktrace)
UnexpectedAlertPresentException: Message: u'Modal dialog present' ; Stacktrace: 
    at nsCommandProcessor.prototype.execute (file:///tmp/tmpeV2K89/extensions/fxdriver@googlecode.com/components/command_processor.js:11520:13)

steps.py 中抛出错误的行是这个。

  world.browser.find_element_by_link_text("Delete User").click()

那个元素的 html 就是这个。

<a href="/users/5910974510923776/delete" onclick="return confirm('Are you sure you want to delete this user?');">Delete User</a>

【问题讨论】:

  • 如果它是一个警报使用(如在 java 中)d.switchTo().alert().accept();(请在 python 中找到等效绑定)。如果它是一个模态对话框,那么我想你可以尝试找到 ok 的定位器。
  • @VivekSingh 它只是driver.switch_to_alert.accept() 甚至driver.switch_to.alert.accept()。我发现这两种方法略有不同,因此认为这对任何为此苦苦挣扎的人提供建议很重要。 driver.switch_to.window() 方法也是如此。

标签: python selenium selenium-webdriver


【解决方案1】:

您需要switch to the alert并接受它:

world.browser.find_element_by_link_text("Delete User").click()
alert = world.browser.switch_to.alert
alert.accept()

【讨论】:

  • 这不会让我进入 world.browser.switch_to_alert()。我试过了,之前一直在线失败,不会越过。
  • @andygimma 所以,在您单击“删除用户”按钮之前似乎打开了一个警报。
  • 我有一个错字,你的回答是正确的。不过,我没有足够的声望点来支持你。谢谢!
  • @1nflktd 好点,虽然它应该是.switch_to.alert()。 (无需致电switch_to)。谢谢。
  • @alecxe:应该是.switch_to.alert() 还是只是.switch_to.alert?我正在使用 Python 2.7 和 Selenium 2.46.0,如果我尝试 .switch_to.alert(),我会得到一个“TypeError: 'Alert' object is not callable”异常。源代码显示 alert 是由 @property 修饰的,所以我认为我们应该在不带括号的情况下调用它。
猜你喜欢
  • 1970-01-01
  • 2020-12-05
  • 2019-09-25
  • 1970-01-01
  • 2022-09-29
  • 2023-03-24
  • 2020-02-03
  • 2017-02-09
  • 2018-09-14
相关资源
最近更新 更多