...
×

Handle checkbox in Playwright Python

We see checkboxes all the time on the web pages. Most of the time we click the boxes to check them or uncheck them. This is common in most of the automation tools.

In Playwright, we can click the checkbox to check it, and it is not recommended in Playwright

from playwright.sync_api import sync_playwright

playwright = sync_playwright().start()
browser = playwright.chromium.launch(headless=False)
page = browser.new_page()
page.goto("https://demo.testercoder.com/dropdowns.html")

page.locator("//input[@type='checkbox']").click()
Check Box Playwright Python Testercoder

But the problem with the above approach is if the checkbox is already checked then our code will click again on the checked box so it will get unchecked.

You will face this kind of scenario on remember me check box and login page, how do we avoid it in automation tools? The playwright provides functions to handle checkboxes either to check or uncheck.

Check:

The check function makes sure that the check box is checked, irrespective of whether it is already checked or not

page.locator("//input[@type='checkbox']").check()

Uncheck:

Uncheck methods uncheck a checkbox.

page.locator("//input[@type='checkbox']").uncheck()

is Checked:

Sometimes you might be in a position to see whether a checkbox is checked and perform some operation based on the result. You can use the is_checked function to know whether a checkbox is checked or not.

page.locator("//input[@type='checkbox']").is_checked()

Author :

Pavankumar Nagaraj is an automation testing expert with over 12 years of experience, specializing in tools like Selenium, Protractor, Puppeteer, and Playwright, and skilled in Java, Python, and JavaScript

Pavankumar Nagaraj
Pavankumar Nagaraj

Pavankumar Nagaraj is an automation testing expert with over 12 years of experience, specializing in tools like Selenium, Protractor, Puppeteer, and Playwright, and skilled in Java, Python, and JavaScript

Seraphinite AcceleratorOptimized by Seraphinite Accelerator
Turns on site high speed to be attractive for people and search engines.