I'm currently working on a Python web application where I need to take a screenshot of a user-provided URL using Playwright in an async function. I'm encountering an issue with asynchronous execution that I can't seem to resolve. Here's the code snippet:
async def embed_url():
url = request.args.get('url')
try:
screenshot_path = await take_screenshot(url)
except Exception as e:
return jsonify({'status': 'error', 'message': f'Error taking screenshot: {e}'}), 500
# ... Other code ...
async def take_screenshot(url):
try:
browser = await launch(headless=True)
page = await browser.newPage()
await page.goto(url)
path = '/public/images/website_screenshots/screen.png'
await page.screenshot({'path': path, 'fullPage': True})
await browser.close()
return path
except Exception as e:
raise e
When I run this code, I encounter the following error:
"Error taking screenshot: signal only works in main thread of the main interpreter"
i tried to use
asyncio.get_event_loop().run_until_complete(take_screenshot(url))
but i got
"Error taking screenshot: This event loop is already running",