NoAlertPresentException in Selenium异常解决

321 阅读1分钟
def test_SMP_login_006():

    wd = webdriver.Chrome()
    wd.implicitly_wait(10)
    wd.get(SMP_URL_LOGIN)

    wd.find_element(By.ID, 'username').send_keys("byhyy")
    wd.find_element(By.ID, 'password').send_keys("sdfsdf")

    wd.find_element(By.ID, 'loginBtn').click()
    msg = wd.switch_to.alert.text

    assert msg == "登录失败: 用户名不存在"
    

使用pytest+selenium时经常碰到alert弹出框的问题 selenium.common.exceptions.NoAlertPresentException: Message: no such alert

原因是该元素可能尚未加载到 DOM 中,因此需要等待该元素加载。

from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

...
  WebDriverWait(wd, 10).until(EC.alert_is_present()) //通过这行代码让webdriver等待页面加载
...