aiohttp使用

tech2024-07-25  48

import requests import re import time from lxml import etree # 导入线程池模块对应的类 from multiprocessing.dummy import Pool import asyncio # 使用该模块中的一个ClienSession对象进行网络化请求 import aiohttp start = time.time() urls = [ 'www.baidu.com', 'www.csdn.com', 'www.bilibili.com' ] async def get_page(url): # requests.get()是基于同步模块的代码,导致异步中断,必须使用基于异步的网络请求模块 # aiohttp:基于异步网络请求的模块 # response = requests.get(url=url) # 所有的with前都要有async修饰 async with aiohttp.ClientSession() as session: # 阻塞操作需要await挂起 # get()、post() # headers自定义头信息UA伪装,params\data,proxy='//ip:port'(是一个字符串) async with await session.get(url) as response: # text()返回字符串形式的响应数据 # read()返回二进制形式的响应数据 # json()返回的就是json对象 # 在获取响应数据之前一定要使用await进行手动挂起 page_text = await response.text() print(page_text) tasks = [] for url in urls: c = get_page(url) # 将协程对象封装到任务对象中 task = asyncio.ensure_future(c) tasks.append(task) loop = asyncio.get_event_loop() loop.run_until_complete(asyncio.wait(tasks)) end = time.time() print(end-start)
最新回复(0)