Home > Net >  Playwright intercept popup/iframe windows
Playwright intercept popup/iframe windows

Time:11-01

I am new to playwright and I'm having trouble to close popup windows when navigating on tumblr

The popup windows for 'cookies Policy' and 'login' never trigger the events: 'page.on("popup",', 'page.once("popup",', 'page.on("dialog",'.

I would like to close the policy popup and login to my account on the following popup. Thanks for the help

My code is as follow:

from time import sleep

from playwright.sync_api import sync_playwright


def close_popups(page):
    print("popup event")
    close_button = page.locator("// button[@class='components-button white-space-normal is-primary']")
    close_button.click()


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

    page.on("popup", close_popups)
    page.once("popup", close_popups)

    page.on("dialog",
            lambda dialog: print("test")
            # lambda dialog: dialog.accept()
            )
    page.goto("https://www.tumblr.com/search/handbags?t=365")

    page.wait_for_load_state(state="domcontentloaded")

    print(page.title())

    # scroll down
    # https://stackoverflow.com/questions/69183922/playwright-auto-scroll-to-bottom-of-infinite-scroll-page
    for i in range(5):  # make the range as long as needed
        page.mouse.wheel(0, 15000)
        sleep(2)
        i  = 1
    # browser.close()
    sleep(2000)

CodePudding user response:

You can click into the button with click function, problem is that the button is inside an iframe. With this should be enough

from time import sleep
from playwright.sync_api import sync_playwright

def do_with_frame(frame):
    if frame.is_visible(".is-primary"):
        frame.click(".is-primary")


with sync_playwright() as p:
    browser = p.chromium.launch(headless=False)
    page_context = browser.new_context()
    page = page_context.new_page()
    page.on("frameattached", do_with_frame)
    page.goto("https://www.tumblr.com/search/handbags?t=365")
    page.wait_for_load_state(state="domcontentloaded")

    print(page.title())

    # scroll down
    # https://stackoverflow.com/questions/69183922/playwright-auto-scroll-to-bottom-of-infinite-scroll-page
    for i in range(5):  # make the range as long as needed
        page.mouse.wheel(0, 15000)
        sleep(2)
        i  = 1
    # browser.close()
    sleep(2)

Take this into account, probably you will find new iframes on the page in the process you want to do. So, if some element is inside an iframe, remember:

  1. Save the iframe element
  2. Use the saved iframe element to make the actions in its elements
  • Related