dafero
dafero

Reputation: 1107

Get text from <span> within a <div> with Selenium

How can I get the text (02/10/2020) inside the span blocks with Selenium?

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

I tried with

driver.find_element_by_class_name("unique_class_date")

but it returns empty.

Edit: this is the code, I am trying to get data from 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
...

Upvotes: 1

Views: 993

Answers (2)

Guy
Guy

Reputation: 50919

You should target the <span> child

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

If this doesn't work either you can use get_attribute()

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

Upvotes: 1

SpicyPhoenix
SpicyPhoenix

Reputation: 308

Add .text at the end.

driver.find_element_by_class_name("unique_class_date").text

Upvotes: 0

Related Questions