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?
You need to take care of a couple of things here:
for
won't work.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
Link to useful documentation:
get_attribute()
method Gets the given attribute or property of the element.text
attribute returns The text of the element.