Python中使用Beautifulsoup4异步HTML解析

2024-09-30 04:27:04 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在制作一个python web scraper脚本。我应该用asyncio来做这个。所以对于异步HTTP请求,我使用AioHTTP。
没关系,但当我尝试制作一个非阻塞应用程序(wait)时,beautifulsoup4将阻止应用程序(因为beauthulsoup4不支持异步)

这就是我尝试过的。在

import asyncio, aiohttp
from bs4 import BeautifulSoup

async def extractLinks(html):
    soup = BeautifulSoup(html, 'html.parser')
    return soup.select(".c-pro-box__title a")

async def getHtml(session, url):
    async with session.get(url) as response:
        return await response.text()

async def loadPage(url):
    async with aiohttp.ClientSession() as session:
        html = await getHtml(session, url)
        links = await extractLinks(html)
        return links

loop = asyncio.get_event_loop()
loop.run_until_complete(loadPage())

extractLinks()将阻止程序流。
所以这有可能使它不阻塞吗?或者除了beauthulsoup4之外,是否还有其他库支持异步?在


Tags: importloopasyncio应用程序urlasyncreturnaiohttp

热门问题