If you’re using Selenium with Python and wondering how to find elements by their JavaScript onclick
attribute, you’re not alone. Many dynamic buttons are defined this way, and traditional locators often fail. In this guide, we’ll show you how to use Selenium to find and click elements using onclick
attributes.
Link to any other blog post on your site (e.g.):
Learn how to upload files with Selenium
Link to a helpful official doc:
Selenium Docs – Locating Elements
Let’s break down how you can locate and interact with these buttons using Selenium.
The Problem
Here is a sample HTML structure:
Both buttons look similar, but what sets them apart is the value passed to the onclick
function.
The Goal
We want to click the second button, the one with:
onclick="javascript:actionPost('Edit', 'LDAP_Test')"
Solution 1: Use the ID (If It’s Static)
If the id
value is consistent and unique, you can simply use:
from selenium import webdriver
driver = webdriver.Chrome()
driver.get("http://your-website.com")
driver.find_element(By.ID, "Edit").click()
Problem: What If the ID Is Dynamic?
Sometimes id
values change between sessions. In that case, target the onclick
content.
Solution 2: Match Using onclick
Attribute
from selenium.webdriver.common.by import By
from selenium import webdriver
driver = webdriver.Chrome()
driver.get("http://your-website.com")
# Match using partial onclick value
button = driver.find_element(By.CSS_SELECTOR, "input[onclick*='actionPost'][onclick*='LDAP_Test']")
button.click()
Why It Works
- The
[onclick*='actionPost']
ensures we only select elements with anonclick
containingactionPost
- The
[onclick*='LDAP_Test']
narrows it down to the exact button we want
Pro Tip
Always inspect the full HTML around the element. If there are other unique patterns (like a parent div, row ID, or class), you can use them to build even more precise selectors.
Conclusion
With Selenium, there’s always a workaround — even for JavaScript-powered buttons. Using attributes like onclick
gives you powerful ways to target exactly what you need.
Keep exploring and automating smartly!