用PyCharm Profile分析异步爬虫效率

栏目: Python · 发布时间: 5年前

内容简介:今天比较忙,水一下下面的代码来源于这个视频里面提到的,github 的链接为:第一个代码如下,就是一个普通的 for 循环爬虫。

今天比较忙,水一下

下面的代码来源于这个视频里面提到的,github 的链接为: github.com/mikeckenned…

第一个代码如下,就是一个普通的 for 循环爬虫。 原文地址

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 工具来具体看看哪些地方比较耗时间。

点击 Profile (文件名称)

用PyCharm Profile分析异步爬虫效率

之后获取到得到一个详细的函数调用关系、耗时图:

用PyCharm Profile分析异步爬虫效率

可以看到 get_html 这个方法占了96.7%的时间。这个程序的 IO 耗时达到了97%,获取 html 的时候,这段时间内程序就在那死等着。如果我们能够让他不要在那儿傻傻地等待 IO 完成,而是开始干些其他有意义的事,就能节省大量的时间。

稍微做一个计算,试用 asyncio 异步抓取,能将时间降低多少?

get_html 这个方法耗时 36.8s ,一共调用了 15 次,说明实际上获取一个链接的 html 的时间为 36.8s / 15 = 2.4s 。**要是全异步的话,获取15个链接的时间还是2.4s。**然后加上 get_title 这个函数的耗时 0.6s ,所以我们估算,改进后的程序将可以用 3s 左右的时间完成,也就是性能能够提升13倍。

再看下改进后的代码。 原文地址

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 图:

用PyCharm Profile分析异步爬虫效率

可见现在耗时为大约3.8s,基本符合我们的预期了。

用PyCharm Profile分析异步爬虫效率
用PyCharm Profile分析异步爬虫效率

我的公众号:全栈不存在的

用PyCharm Profile分析异步爬虫效率

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持 码农网

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

那些让文案绝望的文案

那些让文案绝望的文案

小马宋 / 北京联合出版公司 / 2015-10 / 45

什么文案60年前就在使用互联网思维? 什么文案让一辆小车在崇尚大车的国度畅销不衰? 什么文案让做文案的人产生“既生瑜何生亮”的绝望? 没错,它是甲壳虫。 远在上世纪五六十年代,这些文案让这辆不起眼的小车畅销不衰。 它的文案风趣而又言之凿凿,它的文案机智而又无可辩驳。 它充满自黑精神,善于借势时事热点,懂得乖巧卖萌,也是天生的段子手。 为了让国内读者一睹这一......一起来看看 《那些让文案绝望的文案》 这本书的介绍吧!

JS 压缩/解压工具
JS 压缩/解压工具

在线压缩/解压 JS 代码

RGB转16进制工具
RGB转16进制工具

RGB HEX 互转工具

URL 编码/解码
URL 编码/解码

URL 编码/解码