使用Selenium和python检查是否存在任何警报 [英] Check if any alert exists using selenium with python

查看:153
本文介绍了使用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 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(浏览器, 3 将等待至少需要3秒才能显示受支持的警报。

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

这篇关于使用Selenium和python检查是否存在任何警报的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆