我正在尝试使用python语言的硒为管理用户的网页编写测试。有人可以在此页面中为用户添加角色,如果在添加角色时存在角色,则会发出警报。我不知道警报是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())
但是我也有同样的例外。
此外,我尝试使用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/60380478/