0
0
Selenium Pythontesting~15 mins

Checkbox interactions in Selenium Python - Build an Automation Script

Choose your learning style9 modes available
Verify checkbox selection and deselection
Preconditions (1)
Step 1: Locate the checkbox with id 'subscribe-newsletter'
Step 2: Verify the checkbox is initially not selected
Step 3: Click the checkbox to select it
Step 4: Verify the checkbox is now selected
Step 5: Click the checkbox again to deselect it
Step 6: Verify the checkbox is now not selected
✅ Expected Result: The checkbox can be selected and deselected correctly, and the selection state changes as expected.
Automation Requirements - Selenium with Python
Assertions Needed:
Assert checkbox is initially not selected
Assert checkbox is selected after first click
Assert checkbox is not selected after second click
Best Practices:
Use explicit waits to ensure checkbox is interactable
Use By.ID locator for checkbox
Use assert statements for verification
Use try-finally or context management to close browser
Automated Solution
Selenium Python
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

# Setup WebDriver
with webdriver.Chrome() as driver:
    driver.get('https://example.com/checkbox-demo')

    wait = WebDriverWait(driver, 10)

    # Wait for checkbox to be clickable
    checkbox = wait.until(EC.element_to_be_clickable((By.ID, 'subscribe-newsletter')))

    # Verify checkbox is initially not selected
    assert not checkbox.is_selected(), 'Checkbox should be initially not selected'

    # Click to select checkbox
    checkbox.click()

    # Verify checkbox is selected
    assert checkbox.is_selected(), 'Checkbox should be selected after clicking'

    # Click again to deselect checkbox
    checkbox.click()

    # Verify checkbox is not selected
    assert not checkbox.is_selected(), 'Checkbox should be not selected after second click'

This script uses Selenium WebDriver with Python to automate the checkbox interaction test.

First, it opens the browser and navigates to the checkbox demo page.

It waits explicitly until the checkbox with id 'subscribe-newsletter' is clickable to avoid timing issues.

Then it asserts the checkbox is initially not selected.

Next, it clicks the checkbox to select it and asserts it is selected.

Then it clicks again to deselect and asserts it is not selected.

The use of with statement ensures the browser closes automatically after the test.

Common Mistakes - 3 Pitfalls
Using time.sleep() instead of explicit waits
Using incorrect locator like XPath with absolute path
Not verifying checkbox state before and after clicks
Bonus Challenge

Now add data-driven testing with 3 different checkboxes having ids 'subscribe-newsletter', 'accept-terms', and 'receive-updates'. Verify selection and deselection for each.

Show Hint