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()
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()
Posts You Might Like
- Why playwright is better than selenium webdriver, is it?
- Handle dropdowns in Playwright Python
- Open the browser and Close in Playwright Python
- Handle checkbox in Playwright Python
- Element Operations in Playwright Python
- Handle IFrames in Playwright Python
- Page level commands in Playwright Python
- Element State with Playwright Python