1

I want to get the text of an element in selenium. First I did this:

team1_names = WebDriverWait(driver, 10).until(
    EC.presence_of_element_located((By.CSS_SELECTOR, ".home span"))
)

for kir in team1_names:
    print(kir.text)

It didn’t work out. So I tried this:

team1_name = driver.find_elements_by_css_selector('.home span')
print(team1_name.getText())

so team1_name.text doesn’t work either. So what's wrong with it?

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
  • Hello there, `.text` is the correct way to get the text of an object however we need more context. When you say "it didn't wok out" and it "doesn't work", what happens? Is there an error? - Also: What's the html source look like? Are you getting the right object (i.e. the object with the text)? Can you share a link to the page so someone else can have a look directly and not guess at an answer? – RichEdwards Aug 01 '20 at 16:29

1 Answers1

0

You need to take care of a couple of things here:


Solution

As a solution you need to induce WebDriverWait for the visibility_of_element_located(), and you can use either of the following Locator Strategies:

  • Using CSS_SELECTOR and text attribute:

    print(WebDriverWait(browser, 20).until(EC.visibility_of_element_located((By.CSS_SELECTOR, ".home span"))).text)
    
  • Using XPATH and get_attribute():

    print(WebDriverWait(browser, 20).until(EC.visibility_of_element_located((By.XPATH, "//*[@class='home']//span"))).get_attribute("innerHTML"))
    
  • Note: You have to add the following imports:

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

You can find a relevant discussion in How to retrieve the text of a WebElement using Selenium - Python


Outro

Link to useful documentation:

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
undetected Selenium
  • 183,867
  • 41
  • 278
  • 352