0
0
Selenium Pythontesting~5 mins

Click actions in Selenium Python

Choose your learning style9 modes available
Introduction

Click actions let your test press buttons or links on a webpage automatically. This helps check if things work when clicked.

You want to test if a button opens a new page.
You need to check if clicking a link shows the right content.
You want to simulate a user pressing a checkbox or radio button.
You want to test if clicking a menu item opens a dropdown.
You want to verify that clicking a submit button sends a form.
Syntax
Selenium Python
element.click()

element is the web element you want to click, found using a locator.

Make sure the element is visible and clickable before calling click().

Examples
Click a button found by its ID "submit".
Selenium Python
button = driver.find_element(By.ID, "submit")
button.click()
Click a link with the text "Home".
Selenium Python
link = driver.find_element(By.LINK_TEXT, "Home")
link.click()
Click a checkbox using a CSS selector.
Selenium Python
checkbox = driver.find_element(By.CSS_SELECTOR, "input[type='checkbox']")
checkbox.click()
Sample Program

This script opens a webpage with a custom checkbox, clicks the checkbox label to toggle it, waits 2 seconds, then prints if the checkbox is selected (checked). Finally, it closes the browser.

Selenium Python
from selenium import webdriver
from selenium.webdriver.common.by import By
import time

# Setup driver (make sure chromedriver is in PATH)
driver = webdriver.Chrome()

# Open example page
driver.get("https://www.w3schools.com/howto/howto_css_custom_checkbox.asp")

# Find the first checkbox label and click it
checkbox_label = driver.find_element(By.CSS_SELECTOR, ".container")
checkbox_label.click()

# Wait a moment to see the effect
time.sleep(2)

# Check if checkbox is selected
checkbox = driver.find_element(By.CSS_SELECTOR, "input[type='checkbox']")
print("Checkbox selected:", checkbox.is_selected())

# Close browser
driver.quit()
OutputSuccess
Important Notes

Always wait or check that the element is ready before clicking to avoid errors.

If click does not work, try scrolling the element into view first.

Use explicit waits in real tests to wait for elements to be clickable.

Summary

Click actions simulate user clicks on web elements.

Use element.click() after finding the element.

Ensure the element is visible and ready before clicking.