Search code examples
pythonplaywrightplaywright-python

How to handle dialog with playwright freely


Firstly, i know how to handle dialog,but i don't know how to handle as i wanted. For example, there is a Prompt,when i click it the first time,i like to enter "123" and accept,when i click it the second time,i like to enter "456" and accept.

code like:

from playwright.sync_api import sync_playwright

viewport={"width":1920,"height":1080}
p = sync_playwright().__enter__()
browser = p.chromium.launch(headless=False)
context = browser.new_context(viewport=viewport)
page = context.new_page()
page.goto("http://autopract.com/selenium/alert5/")

page.on("dialog",lambda d:d.accept("123"))
page.locator("#prompt-button").click()

page.on("dialog",lambda d:d.accept("456"))
page.locator("#prompt-button").click()

i had tried.But always listen to the first page.on() . How should i do?


Solution

  • You could do something like this

    acceptWith = "123"
    page.on("dialog",lambda d:d.accept(acceptWith))
    page.locator("#prompt-button").click()
    
    acceptWith = "456"
    page.locator("#prompt-button").click()