python调用url_使用python中的aiohttp获取多个URL

In a previous question, a user suggested the following approach for fetching multiple urls (API calls) with aiohttp:

import asyncio

import aiohttp

url_list = ['https://api.pushshift.io/reddit/search/comment/?q=Nestle&size=30&after=1530396000&before=1530436000', 'https://api.pushshift.io/reddit/search/comment/?q=Nestle&size=30&after=1530436000&before=1530476000']

async def fetch(session, url):

async with session.get(url) as response:

return await response.json()['data']

async def fetch_all(session, urls, loop):

results = await asyncio.gather(*[loop.create_task(fetch(session, url)) for url in urls], return_exceptions= True)

return results

if __name__=='__main__':

loop = asyncio.get_event_loop()

urls = url_list

with aiohttp.ClientSession(loop=loop) as session:

htmls = loop.run_until_complete(fetch_all(session, urls, loop))

print(htmls)

However, this results in only returning Attribute errors:

[AttributeError('__aexit__',), AttributeError('__aexit__',)]

(which I enabled, otherwhise it would just break). I really hope there is somebody here, who can help with this, it is still kind of hard to find resources for asyncio etc. The returned data is in json format. In the end I would like to put all json dicts in a list.

解决方案

Working example:

import asyncio

import aiohttp

import ssl

url_list = ['https://api.pushshift.io/reddit/search/comment/?q=Nestle&size=30&after=1530396000&before=1530436000',

'https://api.pushshift.io/reddit/search/comment/?q=Nestle&size=30&after=1530436000&before=1530476000']

async def fetch(session, url):

async with session.get(url, ssl=ssl.SSLContext()) as response:

return await response.json()

async def fetch_all(urls, loop):

async with aiohttp.ClientSession(loop=loop) as session:

results = await asyncio.gather(*[fetch(session, url) for url in urls], return_exceptions=True)

return results

if __name__ == '__main__':

loop = asyncio.get_event_loop()

urls = url_list

htmls = loop.run_until_complete(fetch_all(urls, loop))

print(htmls)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值