【问题标题】:python selenium - how can i find out exactly when an alert happens?python selenium - 我如何才能准确地找出警报发生的时间?
【发布时间】:2021-06-07 21:34:22
【问题描述】:
我想知道警报何时发生,以便自动接受。我在代码的不同位置放置了self.driver.switch_to.alert.accept(),但我总是得到selenium.common.exceptions.NoAlertPresentException。当我不把它放在任何地方时,我会得到一个selenium.common.exceptions.UnexpectedAlertPresentException。当我使用 expected_conditions 时,我得到一个 selenium.common.exceptions.TimeoutException。我现在不知道该怎么办。有人可以帮忙吗?
Python/Django 后端。使用 Selenium (Firefox)
【问题讨论】:
标签:
python
django
selenium
firefox
【解决方案1】:
我认为没有办法解决这个问题,但如果你知道它会发生,请使用 try-catch 块创建一个 while 循环,直到警报发生
【解决方案2】:
在这种情况下最好有显式等待:
Alert's 我们知道,对吧?
如果您执行let's say 5 steps manually,然后您希望弹出警报,则自动执行完全相同的步骤。
让我们谈谈不同的场景,其中有一个user name Input field,直到我们有一个submit button,现在如果您在该输入字段中没有提供任何内容并点击提交,您会收到一个Alert,上面写着“Hey ! you must enter a user name in order to proceed”。
现在在同样的情况下,当我们将这个场景自动化时,执行确切的步骤:
-
Python - Selenium 不会在 User Name input field 中输入任何内容。
-
Python - Selenium 将直接click on Submit button。
-
Python - Selenium 预计会弹出 Alert,并像这样将switch over 发送给它:
alert_pop_up = driver.switch_to.alert
alert_pop_up.accept()
在大多数情况下,这应该有效,但包括Explicit wait 在内没有任何危害。
wait = WebDriverWait(driver, 10)
wait.until(EC.alert_is_present())