【问题标题】:How to extract the text from the HTML using Selenium and Python如何使用 Selenium 和 Python 从 HTML 中提取文本
【发布时间】:2020-11-05 19:24:36
【问题描述】:

我有这个 HTML:

并且我想要得到这个文本rataoriginal”。 (这段文字变了,我需要这部分代码作为文字)

我试过了

xpath = "//span[@class='_5h6Y_ _3Whw5 selectable-text invisible-space copyable-text']"
auxa = driver.find_element_by_xpath(xpath).text
print(auxa)

但它的打印结果与 print("\n") 相同。我暂时不想使用 beaultifulsoup。

此 HTML 来自“https://web.whatsapp.com”

【问题讨论】:

    标签: python selenium xpath css-selectors webdriverwait


    【解决方案1】:

    //*[contains(text(),"rataoriginal")] 请使用这个xpath

    【讨论】:

    • 你好。我不想选择这个元素,我需要得到这个文本,这意味着这个文本会改变。
    • 你可以通过 gettext();在硒中
    【解决方案2】:

    WebElement 是一个动态元素,因此要打印您必须为visibility_of_element_located() 诱导WebDriverWait 的值,您可以使用以下Locator Strategies 之一:

    • 使用CSS_SELECTOR

      print(WebDriverWait(driver, 20).until(EC.visibility_of_element_located((By.CSS_SELECTOR, "span.selectable-text.invisible-space.copyable-text[dir='auto']"))).text)
      
    • 使用XPATH

      print(WebDriverWait(driver, 20).until(EC.visibility_of_element_located((By.XPATH, "//span[contains(@class, '') and contains(@class, 'invisible-space')][contains(@class, '') and @dir='auto']"))).text)
      
    • 注意:您必须添加以下导入:

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

    参考文献

    您可以在以下位置找到相关讨论:

    【讨论】:

      猜你喜欢
      • 2020-11-11
      • 2020-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-07-21
      • 2020-09-24
      • 2022-01-03
      相关资源
      最近更新 更多