如何等待内容(文本)不为空的元素?我尝试使用//*[@id="test" and text() != ""]
选择xpath,但WebDriverWait#until
的返回不会检索元素。
我的代码:
selector = '//*[@id="test" and text() != ""]'
element = WebDriverWait(driver, timeout).until(
expected_conditions.presence_of_element_located((By.XPATH, selector))
)
我想获取元素的文本内容。我试过了:
print element.text # prints 0
如果我只打印element
,则输出为<selenium.webdriver.remote.webelement.WebElement(session="xxx", element="xxx")>
。有什么问题?
我试图获得的div有这样的结构:
<div>
Test:
<div id="test"><b>this text here</b></div>
</div>
答案 0 :(得分:1)
您可以通过xpath等待具有非空文本的元素,如下所示:
xpath = "//*[@id='test']"
WebDriverWait(driver, 30).until(lambda driver: driver.find_element_by_xpath(xpath).text.strip() != '')
答案 1 :(得分:0)
text()
xpath函数在这种情况下无济于事,因为它不会考虑子元素的文本。您实际上需要在预期条件中调用.text
。 You can create a custom one:
from selenium.webdriver.support import expected_conditions as EC
class wait_for_non_empty_text(object):
def __init__(self, locator):
self.locator = locator
def __call__(self, driver):
try:
element_text = EC._find_element(driver, self.locator).text.strip()
return element_text != ""
except StaleElementReferenceException:
return False
用法:
wait = WebDriverWait(driver, timeout)
element = wait.until(
wait_for_non_empty_text((By.ID, "test"))
)
print(element.text)