Skip to content
CodeKruPro

Click a Button through execute_script

65/80

Click a Button through execute_script

A JavaScript click calls the element click function from the page. Use it on #leftClick and print the text afterward.

Task:

  1. Find #leftClick
  2. Click it with execute_script
  3. Print the button text

Print the lines below exactly.

Expected output:

After JS click: I was left-clicked!

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

  1. Find the button by its id and keep the element in a variable.
  2. Run execute_script with a snippet that clicks arguments[0], and pass the button as the argument.
  3. Read the button's text property after the script, not before.
  4. 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.

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.

main.py
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()