如何验证元素包含任何文本?
我经常需要等到一个AJAX请求完成后,才能在我的页面元素中添加文本。我知道怎么用WebDriverWait来等待特定的文本出现在元素里,但我不知道怎么等到元素里有任何文本。我想避免使用一个一直检查元素文本是否为空的循环。
这是我用来查找特定文本的代码:
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')
有没有办法检查是否有任何文本或者非空字符串呢?
1 个回答
15
你可以使用 By.XPATH
,并在 xpath 表达式中检查 text()
是否不为空:
EC.presence_of_element_located((By.XPATH, '//*[@id="myElem" and text() != ""]'))
顺便说一下,我在这里使用的是 presence_of_element_located()
:
这是一个用来检查页面上某个元素是否存在的期望条件。这并不一定意味着这个元素是可见的。
完整代码:
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')