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

编程入门 行业动态 更新时间:2024-10-25 07:31:27
本文介绍了使用Selenium和python检查是否存在任何警报的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

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

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:

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"

但是它没有用,我得到了 UnexpectedAlertPresentException。 我也尝试过这样:

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

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())

但是我有同样的例外。 此外,我尝试使用Firebug访问警报,以检查是否可以访问其属性,但是右键单击已禁用。 我需要非常快速的解决方案,即使使用其他语言也是如此。我仍然可以理解这种方法。 我将不胜感激。

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.

推荐答案

我要做的是在要点之前使用WebDriverWait设置条件延迟我希望看到警报,然后切换到它,就像这样:

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:

from selenium import webdriver from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC from seleniummon.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(浏览器, 3 )将等待至少需要3秒才能显示受支持的警报。

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

更多推荐

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

本文发布于:2023-11-27 16:05:19,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1638676.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:警报   是否存在   Selenium   python

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!