[Python] How can multiple buttons in Streamlit call the same Playwright page object?

Discussão em 'Python' iniciado por Stack, Fevereiro 3, 2025.

  1. Stack

    Stack Membro Participativo

    My operating environment is:

    • Windows 11, Python 3.13
    • Streamlit = 1.41.1
    • Playwright = 1.49.1

    Now, using Streamlit, I need to create three buttons. When the first button is pressed, it should use Playwright to open a web page in the browser. When the second button is pressed, it should use Playwright to take a screenshot of the web page. When the third button is pressed, it should use Playwright to close the window.

    The problem I encounter is how to call the same page object when the GUI is re-run. Here is my code:

    import streamlit as st
    from playwright.async_api import async_playwright
    import asyncio
    import nest_asyncio
    # apply nest_asyncio
    nest_asyncio.apply()
    # switch to ProactorEventLoop
    if st.runtime.exists():
    asyncio.set_event_loop_policy(asyncio.WindowsProactorEventLoopPolicy())

    # initialize session_state
    if "browser" not in st.session_state:
    st.session_state.browser = None
    if "page" not in st.session_state:
    st.session_state.page = None

    async def open_browser():
    playwright = await async_playwright().start()
    st.session_state.browser = await playwright.chromium.launch(headless=False)
    st.session_state.page = await st.session_state.browser.new_page()
    await st.session_state.page.goto("https://www.baidu.com")
    st.success("webpage opened")

    async def take_screenshot():
    if st.session_state.page:
    await st.session_state.page.screenshot(path="screenshot.png")
    st.success("snapshot saved as screenshot.png")
    else:
    st.error("please open the webpage first")

    async def close_browser():
    if st.session_state.browser:
    await st.session_state.browser.close()
    st.session_state.browser = None
    st.session_state.page = None
    st.success("browser closed")
    else:
    st.error("browser not opened")

    # Streamlit gui
    st.title("Playwright and Streamlit integration")

    if st.button("open"):
    asyncio.run(open_browser())

    if st.button("snapshot"):
    asyncio.run(take_screenshot())

    if st.button("close"):
    asyncio.run(close_browser())


    When I run the code, after click the “open” button, the target page opened as expected, but when I click the “snapshot” button, the streamlit page keeps “running” without any error printing!

    I am not familiar with Python Asyncio.

    For the 3 designed button, I expect:

    1. click btn "open", the target webpage opened, this has been achieved
    2. then, click btn "snapshot", it will take snapshot for the target webpage, this blocked
    3. then click btn "close", it will close the target webpage.

    How can I fix this behavior?

    Continue reading...

Compartilhe esta Página