如何检查元素是否使用Selenium和Python更改了其类?

2024-06-28 10:03:19 发布

您现在位置: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. 我无法输出此errors的内容;我该怎么做? 谢谢你们!祝你今天愉快

Tags: anddividaddressemailloginerroralert
1条回答
网友
1楼 · 发布于 2024-06-28 10:03:19

问题1。我应该如何检查未成功登录

基本上,您可以将登录代码封装在一个文件中,尝试除外:

代码:

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")

相关问题 更多 >