问题
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