Sometimes, normal click actions in Selenium don't work because of hidden elements or overlays. Using JavaScript to click helps to click elements directly.
Clicking with JavaScript in Selenium Python
driver.execute_script("arguments[0].click();", element)driver is your Selenium WebDriver instance.
element is the WebElement you want to click.
button = driver.find_element(By.ID, "submit") driver.execute_script("arguments[0].click();", button)
link = driver.find_element(By.CSS_SELECTOR, ".nav-link") driver.execute_script("arguments[0].click();", link)
This script opens a page with a button inside an iframe. It switches to the iframe, finds the button, clicks it using JavaScript, waits 2 seconds, finds the demo paragraph, then prints its new text to confirm the click worked.
from selenium import webdriver from selenium.webdriver.common.by import By import time # Setup WebDriver driver = webdriver.Chrome() # Open example page driver.get("https://www.w3schools.com/jsref/tryit.asp?filename=tryjsref_onclick") # Switch to iframe where button is driver.switch_to.frame("iframeResult") # Find the button button = driver.find_element(By.TAG_NAME, "button") # Click using JavaScript driver.execute_script("arguments[0].click();", button) # Wait to see the result time.sleep(2) # Check if the demo text was updated demo = driver.find_element(By.ID, "demo") new_text = demo.text print(new_text) # Close browser driver.quit()
JavaScript click bypasses Selenium's normal checks, so use it only when normal click fails.
Make sure the element is visible and interactable before clicking.
Switch to the correct iframe if the element is inside one.
Use JavaScript click to handle tricky elements that block normal clicks.
The syntax is simple: execute_script with arguments[0].click() and the element.
Always verify the click worked by checking page changes or element states.