【问题标题】:Get text from <span> within a <div> with Selenium使用 Selenium 从 <div> 中的 <span> 获取文本
【发布时间】:2020-05-25 22:55:04
【问题描述】:

如何使用 Selenium 在 span 块中获取文本 (02/10/2020)?

<div class="unique_class_date">
  <span>02/10/2020</span>
</div>

我试过了

driver.find_element_by_class_name("unique_class_date")

但它返回空。

编辑:这是代码,我正在尝试从 Bloomberg 获取数据:

import selenium.webdriver
from selenium.webdriver.firefox.options import Options as FirefoxOptions
options = FirefoxOptions()
options.headless = True
driver = selenium.webdriver.Firefox(options=options)
dateclass = "time__245ca7bb"

url = "https://www.bloomberg.com/quote/TSLA:US"
driver.get(url)
last_update = driver.find_element_by_class_name(dateclass).text # sadly, this returns empty
...

【问题讨论】:

    标签: python selenium selenium-webdriver


    【解决方案1】:

    在末尾添加.text

    driver.find_element_by_class_name("unique_class_date").text
    

    【讨论】:

    • 对不起,是的,我已经试过了。我应该说driver.find_element_by_class_name("unique_class_date").text 返回空。谢谢!
    • 啊。你介意展示整个代码吗?或者至少是使用它的部分。
    【解决方案2】:

    您应该定位&lt;span&gt; 孩子

    driver.find_element_by_css_selector(".unique_class_date > span").text
    

    如果这不起作用,您可以使用get_attribute()

    element = driver.find_element_by_css_selector(".unique_class_date > span")
    element.get_attribute("textContent")
    #or
    element.get_attribute("innerText")
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-07-04
      • 2018-07-01
      • 2023-03-05
      • 2019-05-20
      • 2015-04-05
      • 1970-01-01
      相关资源
      最近更新 更多