简体   繁体   English

在 Google colab 上运行 Playwright 会出现错误:asyncio.run() cannot be called from a running event loop

[英]Running Playwright on Google colab gives error : asyncio.run() cannot be called from a running event loop

I was trying to run playwright web automation on google colab but can't run the event loop on colab.我试图在 google colab 上运行playwright网络自动化,但无法在 colab 上运行事件循环。

This is what I tried这是我试过的

!pip install playwright
from playwright.sync_api import sync_playwright

with sync_playwright() as p:
    browser = p.firefox.launch(headless=True)
    page = browser.new_page()
    page.goto("https://www.google.com")

    page.wait_for_timeout(3000)
    browser.close()

which gave me error这给了我错误

ERROR:root:An unexpected error occurred while tokenizing input
The following traceback may be corrupted or invalid
The error message is: ('EOF in multi-line string', (1, 33))

---------------------------------------------------------------------------
Error                                     Traceback (most recent call last)
<ipython-input-29-bc0f59648c4a> in <module>()
      1 from playwright.sync_api import sync_playwright
      2 
----> 3 with sync_playwright() as p:
      4     browser = p.firefox.launch(headless=True)
      5     page = browser.new_page()

/usr/local/lib/python3.7/dist-packages/playwright/sync_api/_context_manager.py in __enter__(self)
     44             raise Error(
     45                 """It looks like you are using Playwright Sync API inside the asyncio loop.
---> 46 Please use the Async API instead."""
     47             )
     48 

Error: It looks like you are using Playwright Sync API inside the asyncio loop.
Please use the Async API instead.

So I tried using the async API所以我尝试使用异步 API

import time
import asyncio
from playwright.async_api import async_playwright

async def main():
    async with async_playwright() as p:
        browser = await p.chromium.launch(headless=False)
        page = await browser.new_page(storage_state='auth.json')
        await page.goto('https://www.instagram.com/explore/tags/alanzoka/')
        time.sleep(6)
        html = await page.content()

        time.sleep(5)

        # await browser.close()


asyncio.run(main())

But this gave me error但这给了我错误

---------------------------------------------------------------------------
RuntimeError                              Traceback (most recent call last)
<ipython-input-34-c582898e6ee9> in <module>()
     27 
     28 
---> 29 asyncio.run(main())

/usr/lib/python3.7/asyncio/runners.py in run(main, debug)
     32     if events._get_running_loop() is not None:
     33         raise RuntimeError(
---> 34             "asyncio.run() cannot be called from a running event loop")
     35 
     36     if not coroutines.iscoroutine(main):

RuntimeError: asyncio.run() cannot be called from a running event loop

I need a working solution of setting up and using the playwright package on google colab.我需要一个在 google colab 上设置和使用 playwright 包的工作解决方案。

Not sure about Colab, but in a normal Jupyter notebook you do:不确定 Colab,但在普通的 Jupyter 笔记本中,您可以:

import nest_asyncio
nest_asyncio.apply()

Install with pip install nest-asyncio , and then you can run async stuff in a notebook.使用pip install nest-asyncio ,然后您可以在笔记本中运行异步内容。

Edit: You are also trying to run a GUI instance of Chrome, with that headless=False - change that to headless=True , Colab doens't run with a GUI.编辑:您还尝试使用headless=False运行 Chrome 的 GUI 实例 - 将其更改为headless=True ,Colab 不会使用 GUI 运行。

I just found this answer in another SO comment.我刚刚在另一个 SO 评论中找到了这个答案。 I confirmed this works.我确认这有效。 https://stackoverflow.com/a/74518471/15898955 https://stackoverflow.com/a/74518471/15898955

!apt install chromium-chromedriver

!pip install nest_asyncio
!pip install playwright

After you installed all the dependencies above, you can run the playwright script in Colab.安装完以上所有依赖后,就可以在 Colab 中运行 playwright 脚本了。

import nest_asyncio
nest_asyncio.apply()

import asyncio
from playwright.async_api import async_playwright

async def main():
    async with async_playwright() as p:
        browser = await p.chromium.launch_persistent_context(
            executable_path="/usr/bin/chromium-browser",
            user_data_dir="/content/random-user"
        )
        page = await browser.new_page()
        await page.goto("https://google.com")
        title = await page.title()
        print(f"Title: {title}")
        await browser.close()

asyncio.run(main())

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 RuntimeError:无法从正在运行的事件循环中调用 asyncio.run() - RuntimeError: asyncio.run() cannot be called from a running event loop websocket 运行异步函数但返回错误:无法从正在运行的事件循环中调用 asyncio.run() - websocket run async function but returns error: asyncio.run() cannot be called from a running event loop 从 Sanic 函数调用抛出“无法从正在运行的事件循环中调用 asyncio.run()” - Called from Sanic functions throws "asyncio.run() cannot be called from a running event loop" 使用 Jupyter Notebook 时“无法从正在运行的事件循环中调用 asyncio.run()” - "asyncio.run() cannot be called from a running event loop" when using Jupyter Notebook 导入导致“无法从正在运行的事件循环中调用 asyncio.run()”的函数 - Importing functions causing "asyncio.run() cannot be called from a running event loop" 我正在尝试创建一个异步函数并遇到此错误,提示“无法从正在运行的事件循环中调用 asyncio.run()” - I'm trying to make an async function and came across this error saying 'asyncio.run() cannot be called from an running event loop' Python 使用 asyncio.run 并尝试添加任务时 asyncio 循环已经运行 - Python asyncio loop already running when using asyncio.run and trying to add tasks Python:“无法关闭正在运行的事件循环”Asyncio - Python: "Cannot close a running event loop" Asyncio 跟随 asyncio.run() 时 asyncio.get_event_loop() 失败 - asyncio.get_event_loop() fails when following asyncio.run() 在主线程运行的asyncio事件循环中运行无限循环 - run infinite loop in asyncio event loop running off the main thread
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM