Python 结合 asyncio 进行网页抓取
Web Scraping with Python in combination with asyncio
我在 python 中编写了一个脚本来从网页获取一些信息。如果从 asyncio 中取出,代码本身是 运行 完美的。但是,由于我的脚本是同步运行的,所以我想让它通过异步过程,以便它在尽可能短的时间内完成任务,提供最佳性能,而且显然不是以阻塞的方式。因为我从来没有使用过这个 asyncio 库,所以我很困惑如何去做。我试图让我的脚本适应 asyncio 进程,但它似乎不对。如果有人伸出援助之手来完成这件事,我真的很感激他。谢谢是提前。这是我的错误代码:
import requests ; from lxml import html
import asyncio
link = "http://quotes.toscrape.com/"
async def quotes_scraper(base_link):
response = requests.get(base_link)
tree = html.fromstring(response.text)
for titles in tree.cssselect("span.tag-item a.tag"):
processing_docs(base_link + titles.attrib['href'])
async def processing_docs(base_link):
response = requests.get(base_link).text
root = html.fromstring(response)
for soups in root.cssselect("div.quote"):
quote = soups.cssselect("span.text")[0].text
author = soups.cssselect("small.author")[0].text
print(quote, author)
next_page = root.cssselect("li.next a")[0].attrib['href'] if root.cssselect("li.next a") else ""
if next_page:
page_link = link + next_page
processing_docs(page_link)
loop = asyncio.get_event_loop()
loop.run_until_complete(quotes_scraper(link))
loop.close()
执行后,我在控制台中看到的是:
RuntimeWarning: coroutine 'processing_docs' was never awaited
processing_docs(base_link + titles.attrib['href'])
您需要用 await
调用 processing_docs()
。
替换:
processing_docs(base_link + titles.attrib['href'])
与:
await processing_docs(base_link + titles.attrib['href'])
并替换:
processing_docs(page_link)
与:
await processing_docs(page_link)
否则它会尝试 运行 一个同步的异步函数并变得不安!
我在 python 中编写了一个脚本来从网页获取一些信息。如果从 asyncio 中取出,代码本身是 运行 完美的。但是,由于我的脚本是同步运行的,所以我想让它通过异步过程,以便它在尽可能短的时间内完成任务,提供最佳性能,而且显然不是以阻塞的方式。因为我从来没有使用过这个 asyncio 库,所以我很困惑如何去做。我试图让我的脚本适应 asyncio 进程,但它似乎不对。如果有人伸出援助之手来完成这件事,我真的很感激他。谢谢是提前。这是我的错误代码:
import requests ; from lxml import html
import asyncio
link = "http://quotes.toscrape.com/"
async def quotes_scraper(base_link):
response = requests.get(base_link)
tree = html.fromstring(response.text)
for titles in tree.cssselect("span.tag-item a.tag"):
processing_docs(base_link + titles.attrib['href'])
async def processing_docs(base_link):
response = requests.get(base_link).text
root = html.fromstring(response)
for soups in root.cssselect("div.quote"):
quote = soups.cssselect("span.text")[0].text
author = soups.cssselect("small.author")[0].text
print(quote, author)
next_page = root.cssselect("li.next a")[0].attrib['href'] if root.cssselect("li.next a") else ""
if next_page:
page_link = link + next_page
processing_docs(page_link)
loop = asyncio.get_event_loop()
loop.run_until_complete(quotes_scraper(link))
loop.close()
执行后,我在控制台中看到的是:
RuntimeWarning: coroutine 'processing_docs' was never awaited
processing_docs(base_link + titles.attrib['href'])
您需要用 await
调用 processing_docs()
。
替换:
processing_docs(base_link + titles.attrib['href'])
与:
await processing_docs(base_link + titles.attrib['href'])
并替换:
processing_docs(page_link)
与:
await processing_docs(page_link)
否则它会尝试 运行 一个同步的异步函数并变得不安!