How to get the hidden text of an element in Selenium Python?

Sometimes, while working with web pages, we may encounter situations where we have to verify the content of hidden text. However, using the text property in Selenium only retrieves the text that is visible to the user, not the hidden text. This can be a challenge for testers who want to validate the hidden text for their test cases. So, this post will cover various ways of retrieving hidden text in Selenium using Python.

Let’s look at them one by one.

Using get_attribute() method

The textContent property allows retrieving the hidden text of an element and its descendants. Therefore, by obtaining the value of the textContent property, we can also retrieve the hidden text.

Please note that the textContent property retrieves the text content of a node regardless of whether the text is visible or not.

The get_attribute() method in Selenium with Python is used to retrieve the value of a given property. We can use this method to get the value of the textContent property, which will give us our hidden text.

element.get_attribute("textContent")

Let’s try to find the hidden text of the element highlighted in the image below. This element is present on our playground website ( https://testkru.com/Elements/TextMessages ).

Hidden text element

We can use the id “hiddenText” to locate the element using Selenium’s find_element() method.

element = driver.find_element(By.ID, 'hiddenText')

and then use the get_attribute() method to retrieve the hidden text of the element.

element.get_attribute("textContent")

Whole Code

from selenium import webdriver
from selenium.webdriver.common.by import By

driver = webdriver.Chrome()
driver.get("https://testkru.com/Elements/TextMessages")

element = driver.find_element(By.ID, 'hiddenText')
print("Hidden Text: " + element.get_attribute("textContent"))

Output –

Hidden Text:  A Hidden Text
Using execute_script() method

The execute_script() method helps execute the javascript code, and thus, by using the script below, we can retrieve the value of the textContent property.

return arguments[0].textContent

where arguments[0] is the element whose hidden text we want to find.

Whole code

from selenium import webdriver
from selenium.webdriver.common.by import By

driver = webdriver.Chrome()
driver.get("https://testkru.com/Elements/TextMessages")

element = driver.find_element(By.ID, 'hiddenText')
print("Hidden Text: " + driver.execute_script("return arguments[0].textContent",element))

Output –

Hidden Text:  A Hidden Text

We hope that you like the article. If you have any doubts or concerns, please feel free to write us in the comments or mail us at admin@codekru.com.

Related Article –
Liked the article? Share this on

Leave a Comment

Your email address will not be published. Required fields are marked *