python中怎么实现异步url请求
今天就跟大家聊聊有关python中怎么实现异步url请求,可能很多人都不太了解,为了让大家更加了解,小编给大家总结了以下内容,希望大家根据这篇文章可以有所收获。

成都创新互联公司-专业网站定制、快速模板网站建设、高性价比泸溪网站开发、企业建站全套包干低至880元,成熟完善的模板库,直接使用。一站式泸溪网站制作公司更省心,省钱,快速模板网站建设找我们,业务覆盖泸溪地区。费用合理售后完善,10多年实体公司更值得信赖。
# pip install aiohttp
import asyncio
import aiohttp
template = 'http://exercise.kingname.info/exercise_middleware_ip/{page}'
async def get(session, queue):
while True:
try:
page = queue.get_nowait()
except asyncio.QueueEmpty:
return
url = template.format(page=page)
resp = await session.get(url)
print(await resp.text(encoding='utf-8'))
async def main():
async with aiohttp.ClientSession() as session:
queue = asyncio.Queue()
for page in range(1000):
queue.put_nowait(page)
tasks = []
for _ in range(100):
# task = fetch_files(session, queue)
task = get(session, queue)
tasks.append(task)
await asyncio.wait(tasks)
# async def fetch_files(session, queue):
# while True:
# try:
# page = queue.get_nowait()
# except asyncio.QueueEmpty:
# return
# url = template.format(page=page)
# async with session.get(url) as resp:
# with open('{}.txt'.format(page), 'w', encoding='UTF-8') as fd:
# data = await resp.content.read()
# fd.write(data.decode('utf-8'))
loop = asyncio.get_event_loop()
loop.run_until_complete(main())创建了100个协程,并把它提交给asyncio.wait来统一调度。asyncio.wait会在所有协程全部结束的时候才返回
1000个 URL 放在asyncio.Queue生成的一个异步队列里面,每一个协程都通过 while True 不停从这个异步队列里面取 URL 并进行访问,直到异步队列为空,退出
看完上述内容,你们对python中怎么实现异步url请求有进一步的了解吗?如果还想了解更多知识或者相关内容,请关注创新互联行业资讯频道,感谢大家的支持。
标题名称:python中怎么实现异步url请求
本文地址:http://www.jxjierui.cn/article/piddgs.html


咨询
建站咨询
