Hi, Anders
Try this:
import streamlit as st
import asyncio
from playwright.async_api import async_playwright
st.write("Starting the test…")
async def main():
async with async_playwright() as p:
browser = await p.chromium.launch()
page = await browser.new_page()
await page.goto("http://playwright.dev")
title = await page.title()
st.write(title)
await browser.close()
return title
if __name__ == '__main__':
loop = asyncio.ProactorEventLoop()
asyncio.set_event_loop(loop)
title=loop.run_until_complete(main())
print(title)
NickDG give the right direction to solve the problem.
In fact, there are two problems here.
First, Streamlit does not support Playwright’s sync mode, so you need to change all the syncs to async. Here are the steps:
- Put everything into a function and write async before it.
- Change ‘with sync_playwright()’ to ‘with async_playwright’.
- Add await before every operation related to playwright.
This completes the process of changing sync to async, but there is another issue.
Secondly, as pointed out by NickDG, Streamlit seems to be constantly looping itself. In this case, async needs to be protected using a ProactorEventLoop() in order to isolate the execution of playwright.