验证文本 - 使用带有 python 的 Selenium webdriver 来自元素的 innerHTML

Verify text - innerHTML from element using Selenium webdriver with python

正在尝试验证文本存在,而不是断言只是验证

我的尝试:

expected_footer = "© 2020 Sauce Labs. All Rights Reserved. Terms of Service | Privacy Policy"
footer_text = driver.find_elements_by_xpath("//footer/div")
if expected_footer in footer_text:
    print("text visible...")
else:
    pass

大概会有一个带有网页的页脚,所以基本上你需要使用 find_element* 而不是 find_elements* 并且你可以使用以下解决方案:

expected_footer = "© 2020 Sauce Labs. All Rights Reserved. Terms of Service | Privacy Policy"
if expected_footer in WebDriverWait(driver, 20).until(EC.visibility_of_element_located((By.XPATH, "//footer/div"))).text :
    print("text visible...")
else:
    pass

注意:您必须添加以下导入:

from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC

您需要获取单个元素(而不是所有元素的列表),然后从该网络元素中获取文本:

expected_footer = "© 2020 Sauce Labs. All Rights Reserved. Terms of Service | Privacy Policy"
footer_text = driver.find_element_by_xpath("//footer/div").text
if expected_footer in footer_text:
    print("text visible...")
else:
    pass

或者如果你想要所有元素(是否不止一个?)

expected_footer = "© 2020 Sauce Labs. All Rights Reserved. Terms of Service | Privacy Policy"
footers = driver.find_elements_by_xpath("//footer/div")
if expected_footer in footers[0].text:
    print("text visible...")
else:
    pass