Assert if text within an element contains specific partial text

痞子三分冷 提交于 2020-11-25 04:36:07

问题


I have an element within tag that has release notes. I have to validate if it contains specific text. I am able to extract the text using following code:

WebDriverWait(self.driver, 10).until(EC.visibility_of_element_located((By.XPATH, ManageSoftware.release_notes_xpath))).get_attribute("innerHTML")

How do I assert if it contain a specific text, say "abc". Is there any function like contains() or isPresent() that I can use here?

The code that I am working on is:

<div id="dialog" class="ui-dialog-content ui-widget-content" style="width: auto; min-height: 0px; max-height: none; height: 483px;">
<pre> 
Text is here.
</pre>
</div>

回答1:


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:

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


来源:https://stackoverflow.com/questions/56467104/assert-if-text-within-an-element-contains-specific-partial-text

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!