每隔5秒在硒python中打印一次移动文本

时间:2018-12-11 10:51:05

标签: python selenium selenium-webdriver

我需要每5秒打印一次移动的文本,以下是html代码:

HTML:

<span class="cd-words-wrapper" style="width: 1170px;">
    <b class="is-hidden">Test</b>
    <b class="is-hidden">Test</b>
    <b class="is-visible">Test</b>
    <b class="is-hidden">Test</b>
</span>

我的Python代码:

 Text = driver.find_elements_by_xpath(self.header)
        time.sleep(5)
        print(Text.text)

以上是获取文本的错误方法。请帮我解决这个问题。

1 个答案:

答案 0 :(得分:3)

如果您希望在新b节点中出现文本后立即进行打印,请尝试以下代码:

from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

while True:
    text_node = WebDriverWait(driver, 10).until(visibility_of_element_located((By.CSS_SELECTOR, '.cd-words-wrapper > .is-visible')))
    print(text_node.text)
    WebDriverWait(driver, 10).until(lambda driver: text_node.get_attribute('class') == "is-hidden")

如果只想打印所有文本节点:

for text_node in driver.find_elements_by_css_selector('.cd-words-wrapper > b'):
    print(text_node.get_attribute('textContent'))