利用PyCharm Profile分析異步爬蟲效率詳解
今天比較忙,水一下
下面的代碼來源于這個視頻里面提到的,github 的鏈接為:github.com/mikeckenned…(本地下載)
第一個代碼如下,就是一個普通的 for 循環(huán)爬蟲。原文地址。
import requests import bs4 from colorama import Fore def main(): get_title_range() print("Done.") def get_html(episode_number: int) -> str: print(Fore.YELLOW + f"Getting HTML for episode {episode_number}", flush=True) url = f'https://talkpython.fm/{episode_number}' resp = requests.get(url) resp.raise_for_status() return resp.text def get_title(html: str, episode_number: int) -> str: print(Fore.CYAN + f"Getting TITLE for episode {episode_number}", flush=True) soup = bs4.BeautifulSoup(html, 'html.parser') header = soup.select_one('h1') if not header: return "MISSING" return header.text.strip() def get_title_range(): # Please keep this range pretty small to not DDoS my site. ;) for n in range(185, 200): html = get_html(n) title = get_title(html, n) print(Fore.WHITE + f"Title found: {title}", flush=True) if __name__ == '__main__': main()
這段代碼跑完花了37s,然后我們用 pycharm 的 profiler 工具來具體看看哪些地方比較耗時間。
點(diǎn)擊Profile (文件名稱)
之后獲取到得到一個詳細(xì)的函數(shù)調(diào)用關(guān)系、耗時圖:
可以看到 get_html 這個方法占了96.7%的時間。這個程序的 IO 耗時達(dá)到了97%,獲取 html 的時候,這段時間內(nèi)程序就在那死等著。如果我們能夠讓他不要在那兒傻傻地等待 IO 完成,而是開始干些其他有意義的事,就能節(jié)省大量的時間。
稍微做一個計算,試用asyncio異步抓取,能將時間降低多少?
get_html這個方法耗時36.8s,一共調(diào)用了15次,說明實(shí)際上獲取一個鏈接的 html 的時間為36.8s / 15 = 2.4s。**要是全異步的話,獲取15個鏈接的時間還是2.4s。**然后加上get_title這個函數(shù)的耗時0.6s,所以我們估算,改進(jìn)后的程序?qū)⒖梢杂?3s 左右的時間完成,也就是性能能夠提升13倍。
再看下改進(jìn)后的代碼。原文地址。
import asyncio from asyncio import AbstractEventLoop import aiohttp import requests import bs4 from colorama import Fore def main(): # Create loop loop = asyncio.get_event_loop() loop.run_until_complete(get_title_range(loop)) print("Done.") async def get_html(episode_number: int) -> str: print(Fore.YELLOW + f"Getting HTML for episode {episode_number}", flush=True) # Make this async with aiohttp's ClientSession url = f'https://talkpython.fm/{episode_number}' # resp = await requests.get(url) # resp.raise_for_status() async with aiohttp.ClientSession() as session: async with session.get(url) as resp: resp.raise_for_status() html = await resp.text() return html def get_title(html: str, episode_number: int) -> str: print(Fore.CYAN + f"Getting TITLE for episode {episode_number}", flush=True) soup = bs4.BeautifulSoup(html, 'html.parser') header = soup.select_one('h1') if not header: return "MISSING" return header.text.strip() async def get_title_range(loop: AbstractEventLoop): # Please keep this range pretty small to not DDoS my site. ;) tasks = [] for n in range(190, 200): tasks.append((loop.create_task(get_html(n)), n)) for task, n in tasks: html = await task title = get_title(html, n) print(Fore.WHITE + f"Title found: {title}", flush=True) if __name__ == '__main__': main()
同樣的步驟生成profile 圖:
可見現(xiàn)在耗時為大約3.8s,基本符合我們的預(yù)期了。
總結(jié)
以上就是這篇文章的全部內(nèi)容了,希望本文的內(nèi)容對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,謝謝大家對腳本之家的支持。
- pycharm下打開、執(zhí)行并調(diào)試scrapy爬蟲程序的方法
- pycharm 使用心得(一)安裝和首次使用
- pycharm 使用心得(三)Hello world!
- Python、PyCharm安裝及使用方法(Mac版)詳解
- PyCharm使用教程之搭建Python開發(fā)環(huán)境
- pycharm 使用心得(七)一些實(shí)用功能介紹
- pycharm 使用心得(九)解決No Python interpreter selected的問題
- pycharm 使用心得(五)斷點(diǎn)調(diào)試
- python安裝教程 Pycharm安裝詳細(xì)教程
- pycharm 使用心得(二)設(shè)置字體大小
相關(guān)文章
Linux安裝Python3如何和系統(tǒng)自帶的Python2并存
這篇文章主要介紹了Linux安裝Python3如何和系統(tǒng)自帶的Python2并存,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友可以參考下2020-07-07django1.11.1 models 數(shù)據(jù)庫同步方法
今天小編就為大家分享一篇django1.11.1 models 數(shù)據(jù)庫同步方法,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2018-05-05pycharm打包python項(xiàng)目為exe執(zhí)行文件的實(shí)例代碼
這篇文章主要介紹了pycharm打包python項(xiàng)目為exe執(zhí)行文件,本文通過實(shí)例代碼給大家介紹的非常詳細(xì),對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下2023-07-07python繪制詞云圖最全教程(自定義png形狀、指定字體、顏色)
詞云圖是一種直觀的方式來展示文本數(shù)據(jù),它易于理解,能展示出詞語的頻率使用情況,對于文本分析非常有用,這篇文章主要給大家介紹了python繪制詞云圖(自定義png形狀、指定字體、顏色)的相關(guān)資料,需要的朋友可以參考下2024-05-05Pythonr基于selenium如何實(shí)現(xiàn)不同商城的商品價格差異分析系統(tǒng)
這篇文章主要給大家介紹了關(guān)于Pythonr基于selenium如何實(shí)現(xiàn)不同商城的商品價格差異分析系統(tǒng)的相關(guān)資料,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友可以參考下2022-03-03解決ToPILImage時出現(xiàn)維度報錯問題pic should be 2/3 d
這篇文章主要介紹了解決ToPILImage時出現(xiàn)維度報錯問題pic should be 2/3 dimensional. Got 4 dimensions.具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教2024-02-02