2

Input:

<input type="text" name="username" value="TestLeaf" align="left" style="width:350px" xpath="1">
    <div>**TestLeaf**</div>
</input>

Code in Selenium Python:

textGet = driver.find_element_by_xpath("//input[@name='username' and @value='TestLeaf']").get_text
print(textGet)

Result: Shows the error

"AttributeError: 'WebElement' object has no attribute 'get_text'"

Please assist me that how to get the text in between the starting and ending tag

undetected Selenium
  • 183,867
  • 41
  • 278
  • 352
  • 1
    Does this answer your question? [What's the get\_Text() equivalent in python bindings for Selenium/Webdriver](https://stackoverflow.com/questions/6360939/whats-the-get-text-equivalent-in-python-bindings-for-selenium-webdriver) – nkrivenko Dec 03 '20 at 08:43

2 Answers2

1

To get the text simply do the following.

textGet = driver.find_element_by_xpath("//input[@name='username' and @value='TestLeaf']").text

.get_text is not the valid way to do so.

Arundeep Chohan
  • 9,779
  • 5
  • 15
  • 32
0

This error message...

"AttributeError: 'WebElement' object has no attribute 'get_text'"

...implies that in your program you have invoked the get_text attribute, which is not a valid WebElement attribute. Instead you need to use the text attribute.


Solution

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

  • Using xpath and get_attribute():

    print(driver.find_element_by_xpath("//input[@name='username' and @value='TestLeaf']/div").get_attribute("innerHTML"))
    
  • Using xpath and text attribute:

    print(driver.find_element_by_xpath("//input[@name='username' and @value='TestLeaf']/div").text)
    

Ideally, to print the text you have to induce WebDriverWait for the visibility_of_element_located() and you can use either of the following Locator Strategies:

  • Using xpath and get_attribute():

    print(WebDriverWait(driver, 20).until(EC.visibility_of_element_located((By.XPATH, "/input[@name='username' and @value='TestLeaf']/div"))).get_attribute("innerHTML"))
    
  • Using xpath and text attribute:

    print(WebDriverWait(driver, 20).until(EC.visibility_of_element_located((By.XPATH, "//input[@name='username' and @value='TestLeaf']/div"))).text)
    
  • 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:

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