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

1

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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:

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.