About this lesson
How to make a hidden element visible in Selenium Python with a style change
Selenium Python AssignmentsAdvancedJavaScript
How it works
A p with the inline style visibility: hidden is still in the DOM, so find_element finds it, but is_displayed() returns False and text is an empty string. Selenium reports what a user would see.
Through execute_script you pass the element in as arguments[0] and set its style.visibility property. The browser re-renders at once, and the same object now reports True and returns its text, trimmed even though the markup has a leading space.
Hiding has several forms. Setting display to none also gives False and an empty text, while the textContent attribute still held the words. The element stays the same object after the change, so no second find_element is needed.
About the assignment
You check an element that starts hidden, reveal it with script, and read it again.
What you will do
- Find the hidden paragraph and print its displayed state, converting the
boolwithstr(). - Run a script on the element that sets its visibility style to the value that shows it.
- Print the displayed state again, then print the text on a third line.
- Take the first reading before the change, or the contrast is lost.
Common mistakes
Forgetting str() on the boolean
Adding the
boolto a label stops the script with aTypeError.Passing a string where the element belongs
A string argument fails with
JavascriptException: Cannot set properties of undefined (setting 'visibility').Expecting text from a hidden element
Reading
.textbefore the change returns an empty string without an exception. Blank means hidden, not wordless.
In a real test suite
Forcing an element visible is a diagnostic tool. A test that does it to get past a real hidden control proves nothing about what users can do, so teams mostly use it in throwaway scripts.
Next comes a failure you meet daily: an element that stops working after a reload.
Related lessons
- Check Whether an Element Is DisplayedExplains what
is_displayedreturns for a normal visible element. - Click a Button through execute_scriptPasses an element into
execute_scriptto act on it. - Read Visible TextReads visible text with the
textproperty.
To try one of these calls on any page without a task, open the Online Selenium Python Compiler.
Starter code
The editor above opens with this code. Fill in the TODO lines, then run and submit it.
from selenium import webdriver
from selenium.webdriver.common.by import By
driver = webdriver.Chrome()
try:
driver.get("https://testkru.com/Elements/TextMessages")
# Make #hiddenText visible and print the three lines
finally:
driver.quit()