日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程语言 > python >内容正文

python

python爬虫 单线程的多任务异步协程

發布時間:2025/3/11 python 37 豆豆
生活随笔 收集整理的這篇文章主要介紹了 python爬虫 单线程的多任务异步协程 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

在input()、sleep(2)、request.get()等時,都會導致線程阻塞,協程可以解決IO等操作時的阻塞現象,提高CPU利用效率。

1.單線程的多任務異步協程
main.py

"""=== coding: UTF8 ===""" import asyncio import timeasync def func1():print("hello python1")await asyncio.sleep(2)print("hello python1")async def func2():print("hello python2")await asyncio.sleep(3)print("hello python2")async def func3():print("hello python3")await asyncio.sleep(4)print("hello python3")async def main():# 準備異步協程對象列表tasks = [asyncio.create_task(func1()),asyncio.create_task(func2()),asyncio.create_task(func3())]await asyncio.wait(tasks)""" ======================================== 主函數功能測試 ======================================== """ if __name__ == '__main__':t1 = time.time()# 一次性運行多個任務asyncio.run(main())t2 = time.time()print(t2 - t1) # 打印耗時的時間

運行效果:

"C:\Program Files\Python38\python.exe" E:/PythonSourceCode/test/main.py hello python1 hello python2 hello python3 hello python1 hello python2 hello python3 4.022439956665039Process finished with exit code 0

2.單線程的多任務異步協程在爬蟲領域的模擬應用
只是模擬,可以作為模板,在實際爬蟲時,需要重點解決

await asyncio.sleep(3) # 模擬網絡請求(網絡耗時)

main.py

"""=== coding: UTF8 ===""" import asyncio import time# 在爬蟲領域的應用 async def download(url):print("準備開始下載")await asyncio.sleep(3) # 模擬網絡請求(網絡耗時)print("下載完成")async def main():urls = ["https://www.hao123.com/", "https://www.baidu.com/", "https://www.bilibili.com/"]# 準備異步協程對象列表tasks = []for url in urls:d = asyncio.create_task(download(url))tasks.append(d)await asyncio.wait(tasks)""" ======================================== 主函數功能測試 ======================================== """ if __name__ == '__main__':t1 = time.time()# 一次性運行多個任務asyncio.run(main())t2 = time.time()print(t2 - t1) # 打印耗時的時間

關注公眾號,獲取更多資料

總結

以上是生活随笔為你收集整理的python爬虫 单线程的多任务异步协程的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。