【发布时间】:2019-05-15 02:39:05
【问题描述】:
我用 python 结合pyppeteer 和asyncio 编写了一个脚本,以从其登录页面抓取不同帖子的链接,并最终通过跟踪通向其内页的 url 来获取每个帖子的标题.我这里解析的内容不是动态的。但是,我使用了pyppeteer 和asyncio 来查看它的效率如何asynchronously。
以下脚本运行了一段时间,但随后出现错误:
File "C:\Users\asyncio\tasks.py", line 526, in ensure_future
raise TypeError('An asyncio.Future, a coroutine or an awaitable is '
TypeError: An asyncio.Future, a coroutine or an awaitable is required
这是我到目前为止所写的:
import asyncio
from pyppeteer import launch
link = "https://stackoverflow.com/questions/tagged/web-scraping"
async def fetch(page,url):
await page.goto(url)
linkstorage = []
elements = await page.querySelectorAll('.summary .question-hyperlink')
for element in elements:
linkstorage.append(await page.evaluate('(element) => element.href', element))
tasks = [await browse_all_links(link, page) for link in linkstorage]
results = await asyncio.gather(*tasks)
return results
async def browse_all_links(link, page):
await page.goto(link)
title = await page.querySelectorEval('.question-hyperlink','(e => e.innerText)')
print(title)
async def main(url):
browser = await launch(headless=True,autoClose=False)
page = await browser.newPage()
await fetch(page,url)
if __name__ == '__main__':
loop = asyncio.get_event_loop()
future = asyncio.ensure_future(main(link))
loop.run_until_complete(future)
loop.close()
我的问题:我怎样才能摆脱该错误并异步执行操作?
【问题讨论】:
标签: python python-3.x web-scraping python-asyncio pyppeteer