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

查看:33
本文介绍了使用 selenium 和 python 检查是否存在任何警报的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用 python 语言的 selenium 为管理用户的网页编写测试.在此页面中,有人可以为用户添加角色,如果添加角色时存在角色,则会发出警报.我不知道警报是 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(browser,3) 将等待至少 3 秒以显示受支持的警报.

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

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

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