Search code examples
pythonplaywrightplaywright-python

Playwright how to handle new windows


Im trying to login with steam on https://buff.163.com. My current code looks like this.

from playwright.sync_api import sync_playwright

with sync_playwright() as p:
    browser = p.chromium.launch(headless=False, slow_mo=50)
    page = browser.new_page()
    context = browser.new_context()
    page.goto("https://buff.163.com/market/csgo#tab=selling&page_num=1")
    page.locator("xpath=/html/body/div[1]/div/div[3]/ul/li/a").click()
    popup = page.wait_for_event("popup")
    page.get_by_text("Other login methods").click()

After it clicks the last button a new windows opens. How can i acces elements in there?


Solution

  • Your sequence seems to be a bit out of order. There's a modal after clicking the Login button, then a popup after clicking Other login methods. Try this flow:

    from playwright.sync_api import sync_playwright  # 1.37.0
    
    
    with sync_playwright() as p:
        browser = p.chromium.launch(headless=False, slow_mo=50)
        page = browser.new_page()
        page.goto("<Your URL>")
        page.get_by_role("link", name="Login/Register").click()
        with page.expect_popup() as popup_info:
            page.get_by_text("Other login methods").click()
        popup = popup_info.value
        popup.wait_for_load_state()
        # interact with the popup...
        print(popup.title())