以下是使用Aiohttp库通过页码获取页面响应,直到获得空响应的代码示例:
import aiohttp
import asyncio
async def fetch_page(session, url):
async with session.get(url) as response:
return await response.text()
async def main():
url = 'http://example.com/page={}' # 用于获取页面的URL模板
page = 1
empty_response = False
async with aiohttp.ClientSession() as session:
while not empty_response:
response = await fetch_page(session, url.format(page))
if not response:
empty_response = True
else:
print(f'Response from page {page}: {response}')
page += 1
if __name__ == '__main__':
loop = asyncio.get_event_loop()
loop.run_until_complete(main())
上述代码示例中,fetch_page函数使用aiohttp库发送GET请求并返回页面内容。main函数使用ClientSession来创建一个aiohttp客户端会话,并使用fetch_page函数获取页面响应。
通过不断增加页码,每次获取页面响应,直到获得空响应(即没有内容)为止。在每一次循环中,如果页面响应不为空,则打印响应内容,并将页码增加1。
最后,通过调用asyncio的run_until_complete方法来运行main函数。