import asyncio, aiohttp
async def download_site(url, session):
async with session.get(url) as resp:
print(f"{url} -> {resp.status}")
async def main():
urls = [“https://example.com”, “https://example.org”]
async with aiohttp.ClientSession() as session:
tasks = [download_site(u, session) for u in urls]
await asyncio.gather(*tasks)
if name == “main”:
asyncio.run(main())
使用 httpx(支持同步/异步)
pip install httpx
import asyncio, httpx
async def fetch(url):
async with httpx.AsyncClient() as client:
r = await client.get(url)
return r.status_code
async def main():
urls = [“https://www.example.com”, “https://www.python.org”, “https://www.github.com”]
results = await asyncio.gather(*[fetch(u) for u in urls])
for u, s in zip(urls, results):
print(u, s)
if name == “main”:
asyncio.run(main())