Logo New Black

Mastering Playwright: How to Click on Alert Dialog with Ease & Precision

When dealing with browser dialog pop-ups in Playwright, mastering the technique to handle these efficiently is crucial for automation and testing scenarios. This approach ensures that your scripts can seamlessly interact with alerts, confirmations, and prompts, mimicking user behavior in a natural and controlled manner. By enhancing your Playwright scripts with capabilities to handle browser dialogs, you can elevate the precision and reliability of your web scraping and automation projects. Secured with the best web scraping API, you can achieve unparalleled efficiency, in accessing and manipulating web data with ease, regardless of the complexity of the interactions required by the website you’re working with.

It’s necessary to assign a dialog handler to the page object. This can be achieved using the page.on("dialog", handler) method:

from playwright.sync_api import sync_playwright

with sync_playwright() as p:
    browser = p.chromium.launch(headless=False)
    page = browser.new_page()

    # create a dialog handler that will check message text and press yes/no
    def handle_dialog(dialog):
        if "clear your cart" in dialog.message:
            print(f'clicking "Yes" to {dialog.message}')
            dialog.accept()  # press "Yes"
            dialog.dismiss()  # press "No"
    page.on("dialog", handle_dialog)

    # to test this, let's try web-scraping.dev cart system: 
    # add something to cart
    # try clearing cart which raises a dialog that says "are you sure you want to clear your cart?"
    page.wait_for_selector(".cart-full .cart-item")
    page.click(".cart-full .cart-clear")

    print(f': {page.query_selector(".cart-item .cart-title")}')  # should be None

In the example provided, a dialog handler is assigned to our page object. This handler checks if the dialog message includes the phrase “clear your cart”. If it does, the handler clicks “Yes” to clear the cart. If not, it clicks “No” to cancel the dialog.