admin管理员组文章数量:1310498
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(";)
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:
- click btn "open", the target webpage opened, this has been achieved
- then, click btn "snapshot", it will take snapshot for the target webpage, this blocked
- then click btn "close", it will close the target webpage.
How can I fix this behavior?
本文标签: pythonHow can multiple buttons in Streamlit call the same Playwright page objectStack Overflow
版权声明:本文标题:python - How can multiple buttons in Streamlit call the same Playwright page object? - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1741821876a2399414.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论