以下是官網原話:
Make a Request
Begin by importing the aiohttp module:
import aiohttp
Now, let’s try to get a web-page. For example let’s query http://httpbin.org/get
:
async with aiohttp.ClientSession() as session: async with session.get('http://httpbin.org/get') as resp: print(resp.status) print(await resp.text())
然后,我這里報錯
>>> async with aiohttp.ClientSession() as session:
File "<stdin>", line 1
async with aiohttp.ClientSession() as session:
^
SyntaxError: invalid syntax
一臉懵逼的自己手敲了一遍,結果還是這樣。
搜索發現這篇文章,給出了解決方案:
https://www.v2ex.com/amp/t/339447
import asyncio import aiohttp async def fetch(): async with aiohttp.ClientSession() as session: async with session.get('https://api.github.com/events') as r: print(r.status) print(await r.text()) loop = asyncio.get_event_loop() loop.run_until_complete(fetch()) loop.close()
最那啥的官方文檔,多學習人家requests的官方文檔。