About this lesson
JavaScript click in Selenium Python: pass the element to execute_script
Selenium Python AssignmentsAdvancedJavaScript
How it works
A normal Selenium click acts like a user: it scrolls to the element, checks it can be clicked, and sends a real mouse event. A JavaScript click calls the element's own click function from inside the page, so the handler runs directly and Selenium does none of its usual checks.
The element goes in as the second argument of execute_script, and the script reads it as arguments[0]. Selenium turns the WebElement into the real DOM node. Pass a plain string instead and the browser raises JavascriptException: "arguments[0].click is not a function".
The call returns None, so the proof is the page itself: the button's text changes. The page also switched that button off, and is_enabled() reported False after the click, which explains why a second click may do nothing.
About the assignment
You click the left-click button without Selenium's click method, then read the button again and show how its label changed.
What you will do
- Find the button by its id and keep the element in a variable.
- Run
execute_scriptwith a snippet that clicksarguments[0], and pass the button as the argument. - Read the button's
textproperty after the script, not before. - Print the label and the new text as one line.
Common mistakes
Passing the id instead of the element
The page receives a string, not a node, so the script fails with the "is not a function"
JavascriptException.Reading text too early
Printing before the script runs shows the original label.
Using JavaScript clicks everywhere
It hides real problems. A button covered by a banner clicks fine through script, yet a user could never press it.
In a real test suite
Larger suites keep the JavaScript click in a small helper, used as a fallback when a normal click is intercepted by a sticky bar or animation. Teams log each use so the workaround does not spread.
The next lesson changes a page's own style instead of clicking.
Related lessons
- Click a Button and Read the New TextThe normal click on this button, which you can compare with the script version.
- Scroll an Element into ViewPasses an element into a script the same way.
- Change the Page with JavaScriptChanges an element's style through script, not just clicks it.
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/Buttons")
# Click #leftClick with JavaScript and print its text
finally:
driver.quit()