hi, I’m a novice in using Streamlit.need your help!
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 run the code, after click the “open” button, the target page opened as expected, but when i click the “snapshot” button, the streamlit page keep “running”???
anybody can help?
Using multiprocessing is a better approach when working with Playwright and Streamlit, especially when you need the Playwright code to run in a separate CPU process. This separation ensures that both the Streamlit and Playwright processes are independent of each other, reducing the risk of threading issues or deadlocks. They can then communicate with each other via Inter Process Communication (IPC), which allows for safer and more efficient data exchange between the two processes. Below is an example code you can use.
import streamlit as st
from multiprocessing import Process, Queue
# Initialize session_state
if "browser_process" not in st.session_state:
st.session_state.browser_process = None
if "command_queue" not in st.session_state:
st.session_state.command_queue = Queue()
if "response_queue" not in st.session_state:
st.session_state.response_queue = Queue()
def playwright_process(command_queue, response_queue):
from playwright.sync_api import sync_playwright
with sync_playwright() as playwright:
browser = playwright.chromium.launch(headless=False)
page = browser.new_page()
while True:
command = command_queue.get()
if command == "open":
page.goto("https://www.baidu.com")
response_queue.put("Webpage opened")
elif command == "screenshot":
page.screenshot(path="screenshot.png")
response_queue.put("Snapshot saved as screenshot.png")
elif command == "close":
browser.close()
response_queue.put("Browser closed")
break
def open_browser():
if st.session_state.browser_process is None:
st.session_state.browser_process = Process(target=playwright_process, args=(st.session_state.command_queue, st.session_state.response_queue))
st.session_state.browser_process.start()
st.session_state.command_queue.put("open")
response = st.session_state.response_queue.get()
st.success(response)
else:
st.error("Browser already opened")
def take_screenshot():
if st.session_state.browser_process is not None:
st.session_state.command_queue.put("screenshot")
response = st.session_state.response_queue.get()
st.success(response)
else:
st.error("Please open the browser first")
def close_browser():
if st.session_state.browser_process is not None:
st.session_state.command_queue.put("close")
response = st.session_state.response_queue.get()
st.session_state.browser_process.join()
st.session_state.browser_process = None
st.success(response)
else:
st.error("Browser not opened")
# Streamlit GUI
st.title("Playwright and Streamlit Integration")
# Streamlit buttons to trigger the functions
if st.button("Open Browser"):
open_browser()
if st.button("Take Screenshot"):
take_screenshot()
if st.button("Close Browser"):
close_browser()
Thanks for stopping by! We use cookies to help us understand how you interact with our website.
By clicking “Accept all”, you consent to our use of cookies. For more information, please see our privacy policy.
Cookie settings
Strictly necessary cookies
These cookies are necessary for the website to function and cannot be switched off. They are usually only set in response to actions made by you which amount to a request for services, such as setting your privacy preferences, logging in or filling in forms.
Performance cookies
These cookies allow us to count visits and traffic sources so we can measure and improve the performance of our site. They help us understand how visitors move around the site and which pages are most frequently visited.
Functional cookies
These cookies are used to record your choices and settings, maintain your preferences over time and recognize you when you return to our website. These cookies help us to personalize our content for you and remember your preferences.
Targeting cookies
These cookies may be deployed to our site by our advertising partners to build a profile of your interest and provide you with content that is relevant to you, including showing you relevant ads on other websites.