问题描述
我需要抓取并获取许多(每天5-10k)新闻文章的正文段落的原始文本。我已经编写了一些线程代码,但是鉴于该项目具有高度的I / O约束性,所以我涉足asyncio
。下面的代码片段并不比1线程版本快,也比我的线程版本差得多。谁能告诉我我在做什么错?谢谢!
async def fetch(session,url):
async with session.get(url) as response:
return await response.text()
async def scrape_urls(urls):
results = []
tasks = []
async with aiohttp.ClientSession() as session:
for url in urls:
html = await fetch(session,url)
soup = BeautifulSoup(html,'html.parser')
body = soup.find('div',attrs={'class':'entry-content'})
paras = [normalize('NFKD',para.get_text()) for para in body.find_all('p')]
results.append(paras)
return results
解决方法
await
的意思是“等待直到结果准备好”,因此,当您在每次循环迭代中等待获取时,都将请求(并获取)顺序执行。要并行进行获取,您需要使用asyncio.create_task(fetch(...))
之类的东西将每个fetch
生成为后台任务,然后 then 等待它们,类似于使用线程的方式。或更简单地说,您可以让asyncio.gather
便捷功能为您完成此操作。例如(未试用):
async def fetch(session,url):
async with session.get(url) as response:
return await response.text()
def parse(html):
soup = BeautifulSoup(html,'html.parser')
body = soup.find('div',attrs={'class':'entry-content'})
return [normalize('NFKD',para.get_text())
for para in body.find_all('p')]
async def fetch_and_parse(session,url):
html = await fetch(session,url)
paras = parse(html)
return paras
async def scrape_urls(urls):
async with aiohttp.ClientSession() as session:
return await asyncio.gather(
*(fetch_and_parse(session,url) for url in urls)
)
如果发现它的运行速度仍然比多线程版本慢,则HTML的解析可能会减慢与IO相关的工作。 (默认情况下,Asyncio在单个线程中运行所有内容。)为防止CPU绑定代码干扰asyncio,您可以使用run_in_executor
将解析移至单独的线程:
async def fetch_and_parse(session,url)
loop = asyncio.get_event_loop()
# run parse(html) in a separate thread,and
# resume this coroutine when it completes
paras = await loop.run_in_executor(None,parse,html)
return paras
请注意,run_in_executor
必须等待,因为它会在后台线程完成给定分配时返回一个“唤醒”的等待状态。由于此版本使用asyncio进行IO和线程进行解析,因此它的运行速度应与您的线程版本一样快,但可以扩展到大量并行下载。
最后,如果要使用多个内核并行并行运行 解析,则可以改为使用多处理:
_pool = concurrent.futures.ProcessPoolExecutor()
async def fetch_and_parse(session,url)
loop = asyncio.get_event_loop()
# run parse(html) in a separate process,and
# resume this coroutine when it completes
paras = await loop.run_in_executor(pool,html)
return paras