如何验证元素是否包含任何文本?

时间:2021-11-27 07:22:59

I often need to wait for an AJAX call to add text to an element on my pages after they finish loading. I understand how to use WebDriverWait to wait for specific text to be present in the element, but I don't see how to wait until there is ANY text present. I'm trying to avoid a while loop that keeps checking the element's text isn't == ''.

我经常需要等待一个AJAX调用,在完成加载后在我的页面上的元素中添加文本。我理解如何使用WebDriverWait等待元素中存在特定文本,但我不知道如何等待任何文本存在。我试图避免一个while循环,一直检查元素的文本不是==''。

Here's what I use to find specific text:

这是我用来查找特定文本的内容:

try:
    WebDriverWait(self.driver, 10).until(EC.text_to_be_present_in_element((By.ID, 'myElem'), 'foo'))
except TimeoutException:
    raise Exception('Unable to find text in this element after waiting 10 seconds')

Is there a way to check for any text or a non-empty string?

有没有办法检查任何文本或非空字符串?

1 个解决方案

#1


10  

You can use By.XPATH and check if the text() is non-empty inside the xpath expression:

您可以使用By.XPATH并检查xpath表达式中的text()是否为非空:

EC.presence_of_element_located((By.XPATH, '//*[@id="myElem" and text() != ""]'))

FYI, I'm using presence_of_element_located() here:

仅供参考,我在这里使用了presence_of_element_located():

An expectation for checking that an element is present on the DOM of a page. This does not necessarily mean that the element is visible.

期望检查页面的DOM上是否存在元素。这并不一定意味着该元素是可见的。

Complete code:

完整代码:

try:
    WebDriverWait(self.driver, 10).until(EC.presence_of_element_located((By.XPATH, '//*[@id="myElem" and text() != ""]')))
except TimeoutException:
    raise Exception('Unable to find text in this element after waiting 10 seconds')

#1


10  

You can use By.XPATH and check if the text() is non-empty inside the xpath expression:

您可以使用By.XPATH并检查xpath表达式中的text()是否为非空:

EC.presence_of_element_located((By.XPATH, '//*[@id="myElem" and text() != ""]'))

FYI, I'm using presence_of_element_located() here:

仅供参考,我在这里使用了presence_of_element_located():

An expectation for checking that an element is present on the DOM of a page. This does not necessarily mean that the element is visible.

期望检查页面的DOM上是否存在元素。这并不一定意味着该元素是可见的。

Complete code:

完整代码:

try:
    WebDriverWait(self.driver, 10).until(EC.presence_of_element_located((By.XPATH, '//*[@id="myElem" and text() != ""]')))
except TimeoutException:
    raise Exception('Unable to find text in this element after waiting 10 seconds')