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

Table of Contents

Table of Contents

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 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")".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.

Related Questions

Related Blogs

In the intricate dance of web scraping, where efficiency and respect for the target server’s bandwidth are paramount, mastering the art of rate limiting asynchronous...
Utilizing Playwright for web scraping enables us to navigate pages with infinite scrolling, where content dynamically loads as the user scrolls down. To automate this...
Python offers a variety of HTTP clients suitable for web scraping. However, not all support HTTP2, which can be crucial for avoiding web scraper blocking....