使用 selenium 和 python 检查是否存在任何警报

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19003003/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 12:32:28  来源:igfitidea点击:

Check if any alert exists using selenium with python

pythonseleniumtestingalertwindow-handles

提问by Zeinab Abbasimazar

I'm trying to write a test with selenium in python language for a web page that manages users. In this page someone can add role for users and if a role exists while adding it, an alert raises. I don't know if the alert is a javascript alert or an element of the web page. I want to automatically check the existence of the alert, because checking for the role in the list wastes time and has an enormous load. I tried this:

我正在尝试使用 python 语言的 selenium 为管理用户的网页编写测试。在此页面中,有人可以为用户添加角色,如果添加角色时存在角色,则会发出警报。我不知道警报是 javascript 警报还是网页的元素。我想自动检查警报是否存在,因为检查列表中的角色浪费时间并且负载巨大。我试过这个:

browser = webdriver.Firefox()
browser.get("url")
browser.find_the_element_by_id("add_button").click()
try:
    alert = browser.switch_to_alert()
    alert.accept()
    print "alert accepted"
except:
    print "no alert"

But it didn't work and I got the "UnexpectedAlertPresentException". I also tried this:

但它没有用,我得到了“UnexpectedAlertPresentException”。我也试过这个:

browser = webdriver.Firefox()
browser.get("url")
browser.find_the_element_by_id("add_button").click()
s = set(browser.window_handles)
s.remove(browser.current_window_handle)
browser.switch_to_window(s.pop()) 

But I got the same exception. Additionally, I tried to access the alert with firebug to check if I can get access with its properties, but right click was disabled. I need a solution very quickly, even in other languages. I can understand the approach anyway. I will appreciate any help.

但我得到了同样的例外。此外,我尝试使用 firebug 访问警报以检查是否可以访问其属性,但右键单击被禁用。我很快就需要一个解决方案,即使是其他语言也是如此。无论如何,我可以理解这种方法。我将不胜感激任何帮助。

采纳答案by A.R.

What I do is to set a conditional delay with WebDriverWait just before the point I expect to see the alert, then switch to it, like this:

我所做的是在我希望看到警报的点之前使用 WebDriverWait 设置条件延迟,然后切换到它,如下所示:

from selenium import webdriver
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.common.exceptions import TimeoutException

browser = webdriver.Firefox()
browser.get("url")
browser.find_element_by_id("add_button").click()

try:
    WebDriverWait(browser, 3).until(EC.alert_is_present(),
                                   'Timed out waiting for PA creation ' +
                                   'confirmation popup to appear.')

    alert = browser.switch_to.alert
    alert.accept()
    print("alert accepted")
except TimeoutException:
    print("no alert")

WebDriverWait(browser,3)will wait for at least 3 seconds for a supported alert to appear.

WebDriverWait(browser,3)将等待至少 3 秒钟以显示受支持的警报。

回答by Abhishek Singh

In java we do it like this

在java中我们这样做

WebDriverWait wait3 = new WebDriverWait(driver, 7000);
wait3.until(ExpectedConditions.alertIsPresent());
driver.switchTo().alert().accept();

It will implicitly wait for alert if alert is not present it will throw 'Alert is not present Exceptio' which we can catch and move ahead.

如果警报不存在,它将隐式等待警报,它将抛出“警报不存在异常”,我们可以捕捉并继续前进。

Hope it helps.

希望能帮助到你。

回答by yaobin

I know this is a too late answer and you have solved this question years ago, but I still want to post my analysis and findings for possible future readers' reference.

我知道这是一个为时已晚的答案,您几年前已经解决了这个问题,但我仍然想发布我的分析和发现,以供未来读者参考。

I am working on a Django website development project, and currently there is a bug that once a particular web page is opened, an error message box is popped up. My environment is:

我正在做一个 Django 网站开发项目,目前有一个错误,即一旦打开特定网页,就会弹出一个错误消息框。我的环境是:

  • Django 1.8
  • Python 2.7
  • Selenium 2.46.0
  • 姜戈 1.8
  • 蟒蛇 2.7
  • 硒 2.46.0

I read the document hereabout the "UnexpectedAlertPresentException", and it says:

我在这里阅读了有关“UnexpectedAlertPresentException”的文档,它说:

Thrown when an unexpected alert is appeared.

Usually raised when when an expected modal is blocking webdriver form executing any more commands.

当出现意外警报时抛出。

通常在预期模式阻止 webdriver 表单执行更多命令时引发。

I tested in my project and my findings are:

我在我的项目中进行了测试,我的发现是:

  • When the alert box is up, the find_element_by_Xmethods can succeed.
  • The click() or send_keys() will fail with the "UnexpectedAlertPresentException".
  • 当警报框出现时,这些find_element_by_X方法可以成功。
  • click() 或 send_keys() 将失败并显示“UnexpectedAlertPresentException”。

Therefore, I think the try...catchblock doesn't work because the "UnexpectedAlertPresentException" is thrown in the line of

因此,我认为该try...catch块不起作用,因为“UnexpectedAlertPresentException”被抛出

browser.find_the_element_by_id("add_button").click()

This also means that the alert box may appear as soon as the web page is opened by this line:

这也意味着只要通过这一行打开网页,警报框就会出现:

browser.get("url")

In other words, there might be a problem hidden deeper behind that caused the alert box up as soon as the page is opened. You may need to fix that problem first.

换句话说,可能有一个问题隐藏在更深的背后,导致页面一打开就弹出警告框。您可能需要先解决该问题。

Another thing is: Assuming the alert box showed up afterthis line:

另一件事是:假设警告框出现这一行之后:

browser.find_the_element_by_id("add_button").click()

Then the alert = browser.switch_to_alert()should work well with no exception thrown, which contradicts to what you describe here. This also made me think that the problem is as early as the browser.get("url")line.

然后alert = browser.switch_to_alert()应该可以正常工作,不会抛出异常,这与您在此处描述的内容相矛盾。这也让我觉得问题早browser.get("url")在行。

I'm not very sure how the selected solution helped you solve the problem because my analysis shows the problem lies in a different place. Anyway, I am not asking for reselecting the accepted solution. I just want to share my thoughts for future readers.Apologize in case that I overlooked or misunderstood something in this question which caused my analysis to be wrong (and which wastes your time reading this :-).

我不太确定所选的解决方案如何帮助您解决问题,因为我的分析表明问题出在不同的地方。无论如何,我不是要求重新选择已接受的解决方案。我只是想与未来的读者分享我的想法。如果我忽略或误解了这个问题中的某些内容而导致我的分析错误(并且浪费您的时间阅读此内容:-),请道歉。

回答by Ricardo Valbuena

alert = self.driver.switch_to.alert
    if alert.is_displayed():
        alert.accept()