如何使用Python在Selenium中测试Alert/Popup

use*_*886 2 python selenium python-3.x

我坚持自动化,当我输入错误的用户名和密码时,会弹出"无法登录.尝试不同的用户名"

def test_logonWrongUserName(self):
    self.setUpClass() # Initialize the driver 
    self.sh.navigateToUrl("http://test.com")
    self.sh.member_Login("Foo", "asd") 
Run Code Online (Sandbox Code Playgroud)

现在需要测试警报或弹出窗口(不确定它是警报或弹出窗口),其中包含"无法登录.尝试使用不同的用户名"文本.如果找到文本则测试通过.如果没有,则测试必须失败.

注意:只想添加,在关闭警报/弹出窗口之前,我们无法访问html dom

ale*_*cxe 6

您需要等待警报出现,断言您有预期的文本,然后关闭/ 接受警报:

from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.common.exceptions import TimeoutException

wait = WebDriverWait(driver, 10)
wait.until(EC.alert_is_present())

alert = driver.switch_to.alert
assert "Unable to login. Try different username" in alert.text
alert.accept()
Run Code Online (Sandbox Code Playgroud)