Issue
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?
Solution
You need to take care of a couple of things here:
- presence_of_element_located() is the expectation for checking that an element is present on the DOM of a page. This does not necessarily mean that the element is visible.
- Additionally, presence_of_element_located() returns a WebElement, not a list. Hence, iterating through
for
won't work.
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
andget_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:
- The
get_attribute()
method Gets the given attribute or property of the element. - The
text
attribute returns The text of the element. - Difference between text and innerHTML using Selenium
Answered By - undetected Selenium
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.