-2

So I want to print out "ou" from this HTML via XPath.

<div class="syllable">ou</div>

This is my code:

elem = driver.find_elements_by_xpath('*my xpath*')
for my_elem in elem:
    print(my_elem.text)

I used .text in this code but it just prints out nothing when it runs. It should be printing ou but it just prints nothing at all. If someone could please tell me what I am doing wrong that would be great.

undetected Selenium
  • 183,867
  • 41
  • 278
  • 352
Kip
  • 81
  • 1
  • 5

2 Answers2

0

To print the text ou you can use either of the following Locator Strategies:

  • Using css_selector and get_attribute("innerHTML"):

    print(driver.find_element_by_css_selector("div.syllable").get_attribute("innerHTML"))
    
  • Using xpath and text attribute:

    print(driver.find_element_by_xpath("//div[@class='syllable']").text)
    

Ideally 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(driver, 20).until(EC.visibility_of_element_located((By.CSS_SELECTOR, "div.syllable"))).text)
    
  • Using XPATH and get_attribute():

    print(WebDriverWait(driver, 20).until(EC.visibility_of_element_located((By.XPATH, "//div[@class='syllable']"))).get_attribute("innerHTML"))
    
  • Console Output:

    ou
    
  • 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


References

Link to useful documentation:

undetected Selenium
  • 183,867
  • 41
  • 278
  • 352
0

if you are unable to print the text using .text then use .get_attribute("innerHTML") this will defiantly print out the text.

eg. your code should look like this

    elem = driver.find_elements_by_xpath('*my xpath*').get_attribute("innerHTML")

    for my_elem in elem:
    print(my_elem)
softcode
  • 19
  • 1