您好,登錄后才能下訂單哦!
今天就跟大家聊聊有關(guān)python中怎么實(shí)現(xiàn)異步url請求,可能很多人都不太了解,為了讓大家更加了解,小編給大家總結(jié)了以下內(nèi)容,希望大家根據(jù)這篇文章可以有所收獲。
# 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())
創(chuàng)建了100個(gè)協(xié)程,并把它提交給asyncio.wait來統(tǒng)一調(diào)度。asyncio.wait會(huì)在所有協(xié)程全部結(jié)束的時(shí)候才返回
1000個(gè) URL 放在asyncio.Queue生成的一個(gè)異步隊(duì)列里面,每一個(gè)協(xié)程都通過 while True 不停從這個(gè)異步隊(duì)列里面取 URL 并進(jìn)行訪問,直到異步隊(duì)列為空,退出
看完上述內(nèi)容,你們對python中怎么實(shí)現(xiàn)異步url請求有進(jìn)一步的了解嗎?如果還想了解更多知識(shí)或者相關(guān)內(nèi)容,請關(guān)注億速云行業(yè)資訊頻道,感謝大家的支持。
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。