self_example/Spider/Chapter06_异步爬虫/asyncio/asyncTest2.py

39 lines
891 B
Python
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

# -*- encoding:utf-8 -*-
'''
@Author : dingjiawen
@Date : 2023/12/6 16:20
@Usage : asyncio库 可以使用async和await关键字
@Desc :异步爬虫测试 定义协程 为某一个task绑定回调方法
@参考https://github.dev/Python3WebSpider/AsyncTest
'''
import asyncio
import requests
async def request():
url = 'https://www.baidu.com'
status = requests.get(url)
return status
def callback(task):
print('Status:', task.result())
coroutine = request()
task = asyncio.ensure_future(coroutine)
# 绑定回调,来保证顺序
task.add_done_callback(callback)
print('Task:', task)
loop = asyncio.get_event_loop()
loop.run_until_complete(task)
print('Task:', task)
# 直接通过task.result()也可以直接获取结果达到类似的效果
loop = asyncio.get_event_loop()
loop.run_until_complete(task)
print('Task:', task)
print('Task Result:', task.result())