首页 > 解决方案 > 如何检查元素是否使用 Selenium 和 Python 更改其类?

问题描述

我有一个带有以下 HTML 的网站。首先,元素将是:

<div class="hidden sc-cHGsZl ghXVcK" role="alert" id="login-error"></div>

然后登录失败后会变成:

<div class="sc-cHGsZl ghXVcK" role="alert" id="login-error">
    <span>Incorrect email address and / or password.<br>
     Do you need help <a href="/login/resetpassword?email=xxxxx">logging in</a>?
    </span>
</div>

我目前在做什么:

errors = driver.find_element_by_xpath(
    "//div[@id='login-error']//span[contains(., 'Incorrect email address and / or password.')]")

我有几个问题如下:

  1. 我应该如何检查登录失败?
  2. 我无法输出 this 的内容errors;我该怎么做?谢谢你们!祝你今天过得愉快!

标签: pythonselenium

解决方案


Q1。我应该如何检查登录失败?

基本上,您可以将登录代码包装在try-except 中:

代码 :

try:
    driver.find_element_by_xpath("user name xpath").send_keys('username')
    driver.find_element_by_xpath("password xpath").send_keys('password')
    driver.find_element_by_xpath('login button xpath').click()
    if len(driver.find_elements(By.XPATH, "//span[contains(text(), 'Incorrect email address')]")) > 0:
        print("if code has reached here that means login was not successful")
        # assert login failure here if you want
    else:
        print("login must have been successful since Incorrect email address web element was not found")
except:
    print("something went wrong")
    pass

对于第二个问题,你可以有这条线

print(driver.find_element_by_xpath("//span[contains(text(), 'Incorrect email address')]").text) 

在这一行之后的 if 块中print("if code has reached here that means login was not successful")


推荐阅读