MarquesDev
MarquesDev

Reputation: 77

Text from a Webelement (Selenium + Python)

My case is simple, I just want to take the text from this html bellow:

<yt-formatted-string id="text" title="" class="style-scope ytd-channel-name">Rayra Fortunato</yt-formatted-string>

I'm using Python + Selenium but i can't retrieve the "Rayra Fortunato" from it as a string.

This is my code that isn't working properly.

realName = driver.find_element_by_xpath("//yt-formatted-string[contains(text(),'Rayra Fortunato')]")
realName = realName.get_attribute('text')
print(realName)

or

realName = driver.find_element_by_xpath("//yt-formatted-string[contains(text(),'Rayra Fortunato')]")
realName = realName.text
print(realName)

Any help?

Thanks!

Upvotes: 0

Views: 73

Answers (2)

cruisepandey
cruisepandey

Reputation: 29362

You may need explicit wait as well, however it seems that your locator is correct.

Code :

wait = WebDriverWait(driver, 10)
print(wait.until(EC.element_to_be_clickable((By.XPATH, "//yt-formatted-string[contains(text(),'Rayra Fortunato')]"))).text)

Imports :

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

Upvotes: 1

vitaliis
vitaliis

Reputation: 4212

There are many possible variations you can try. Among them:

locator = driver.find_element_by_xpath('//yt-formatted-string[@id="text"]')
real_name = locator.text

Or

locator = driver.find_element_by_css_selector("text")
real_name = locator.text

Or:

locator = driver.find_element_by_xpath('//yt-formatted-string[@id="text"]')
real_name = locator.get_attribute("innerHTML")

(and the same method with css_selector).

However, this should work for this small html. The real HTML that you are looking at may be much more complex and above solutions might not work. If it's true check the following:

  • Locator is not located inside iframe
  • Locator is not located inside a shadow DOM
  • Page is fully loaded before you are trying to get the text
  • Locators are unique (it's hard to say from your question).

This list may be longer.

Upvotes: 1

Related Questions