我正在尝试用 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"
但它不起作用,我得到了“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())
但我遇到了同样的异常(exception)。 此外,我尝试使用 firebug 访问警报以检查是否可以访问其属性,但右键单击被禁用。 我很快就需要一个解决方案,即使是其他语言。无论如何,我可以理解这种方法。 我将不胜感激。
最佳答案
我所做的是在我希望看到警报的点之前使用 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)
将等待至少 3 秒以显示支持的警报。
关于python - 使用 selenium 和 python 检查是否存在任何警报,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19003003/