×
Handle Checkbox Playwright Python

Handle checkbox in Playwright Python

Written by


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://chercher.tech/practice/dropdowns")
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 :

Senior Software Engineer in Test, with more than a decade of experience in automation tools like Selenium, Playwright, Protractor, and Puppeteer with Python, Java, and JS respectively.