且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

断言元素内的文本是否包含特定的部分文本

更新时间:2023-12-04 23:25:22

要验证所需文本是否存在于任何元素中,您需要使用引发 try-catch {} 块用于 text_to_be_present_in_element()的WebDriverWait ,您可以使用以下

To validate the presence of the desired text within any element you need to use a try-catch{} block inducing WebDriverWait for text_to_be_present_in_element() and you can use either of the following Locator Strategies:

  • 使用 CSS_SELECTOR :

try:
    WebDriverWait(driver, 20).until(EC.text_to_be_present_in_element((By.CSS_SELECTOR, "div.ui-dialog-content.ui-widget-content#dialog>pre"), "Text is here"))
    print("Desired text was present")
except TimeoutException:
    print("Desired text was not present")

  • 使用 XPATH :

    try:
        WebDriverWait(driver, 20).until(EC.text_to_be_present_in_element((By.XPATH, "//div[@class='ui-dialog-content ui-widget-content' and @id='dialog']/pre"), "Text is here"))
        print("Desired text was present")
    except TimeoutException:
        print("Desired text was not present")
    

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

  • Note : You have to add the following imports :

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