This article explains how to handle checkboxes using Selenium in Python. It includes locating checkboxes on a web page using their unique identifiers, verifying their initial selection state, toggling their selection by clicking, and printing the state changes to the console.
1. Import the Necessary Libraries, creating an driver instance and navigating to the specified url.
2. Locate the checkboxes by Id and print their initial selection state using the is_selected() method which is used to determine if a web element is selected or not and returns a boolean value.
3. Toggle the checkbox state, using the click() method toggles the state of the first checkbox (checkbox1).
And finally close the browser.
Final code
import time
from selenium import webdriver
from selenium.webdriver.common.by import By
# Initialize WebDriver
driver = webdriver.Chrome()
# Navigate to the Selenium Web Form Page
driver.get("https://www.selenium.dev/selenium/web/formPage.html")
try:
# Locate the checkboxes using their unique identifiers
checkbox1 = driver.find_element(By.ID, "checky")
checkbox2 = driver.find_element(By.ID, "checkedchecky")
print("initial status", checkbox1.is_selected())
print("initial status of checkbox 2", checkbox2.is_selected())
checkbox1.click()
print("Status after clicking", checkbox1.is_selected())
checkbox2.click()
print("Status after clicking", checkbox2.is_selected())
finally:
# Close the browser
time.sleep(5)
driver.quit()
Output
Similar Posts
How to Handle IFrames in Selenium
How to handles Drop down in selenium
How to Handle Alerts and Popups in Selenium
Locating Strategies in Selenium : Locating by Id
Installing Selenium and Configuring Web Driver
Selenium Python Example: How to run your first Test?