python爬虫 单线程的多任务异步协程
生活随笔
收集整理的這篇文章主要介紹了
python爬虫 单线程的多任务异步协程
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
在input()、sleep(2)、request.get()等時,都會導致線程阻塞,協程可以解決IO等操作時的阻塞現象,提高CPU利用效率。
1.單線程的多任務異步協程
main.py
運行效果:
"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 02.單線程的多任務異步協程在爬蟲領域的模擬應用
只是模擬,可以作為模板,在實際爬蟲時,需要重點解決
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爬虫 单线程的多任务异步协程的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Linux系统下MySQL导出数据库和导
- 下一篇: 【Faster RCNN detect