侯体宗的博客
  • 首页
  • Hyperf版
  • beego仿版
  • 人生(杂谈)
  • 技术
  • 关于我
  • 更多分类
    • 文件下载
    • 文字修仙
    • 中国象棋ai
    • 群聊
    • 九宫格抽奖
    • 拼图
    • 消消乐
    • 相册

利用PyCharm Profile分析异步爬虫效率详解

Python  /  管理员 发布于 5年前   369

今天比较忙,水一下

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

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

import requestsimport bs4from colorama import Foredef 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.textdef 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 (文件名称)

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

可以看到 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 asynciofrom asyncio import AbstractEventLoopimport aiohttpimport requestsimport bs4from colorama import Foredef 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 htmldef 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 图:

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


总结

以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作具有一定的参考学习价值,谢谢大家对AIDI的支持。


  • 上一条:
    利用pyinstaller打包exe文件的基本教程
    下一条:
    PyQt5的PyQtGraph实践系列3之实时数据更新绘制图形
  • 昵称:

    邮箱:

    0条评论 (评论内容有缓存机制,请悉知!)
    最新最热
    • 分类目录
    • 人生(杂谈)
    • 技术
    • linux
    • Java
    • php
    • 框架(架构)
    • 前端
    • ThinkPHP
    • 数据库
    • 微信(小程序)
    • Laravel
    • Redis
    • Docker
    • Go
    • swoole
    • Windows
    • Python
    • 苹果(mac/ios)
    • 相关文章
    • 在python语言中Flask框架的学习及简单功能示例(0个评论)
    • 在Python语言中实现GUI全屏倒计时代码示例(0个评论)
    • Python + zipfile库实现zip文件解压自动化脚本示例(0个评论)
    • python爬虫BeautifulSoup快速抓取网站图片(1个评论)
    • vscode 配置 python3开发环境的方法(0个评论)
    • 近期文章
    • 在go中实现一个常用的先进先出的缓存淘汰算法示例代码(0个评论)
    • 在go+gin中使用"github.com/skip2/go-qrcode"实现url转二维码功能(0个评论)
    • 在go语言中使用api.geonames.org接口实现根据国际邮政编码获取地址信息功能(1个评论)
    • 在go语言中使用github.com/signintech/gopdf实现生成pdf分页文件功能(0个评论)
    • gmail发邮件报错:534 5.7.9 Application-specific password required...解决方案(0个评论)
    • 欧盟关于强迫劳动的规定的官方举报渠道及官方举报网站(0个评论)
    • 在go语言中使用github.com/signintech/gopdf实现生成pdf文件功能(0个评论)
    • Laravel从Accel获得5700万美元A轮融资(0个评论)
    • 在go + gin中gorm实现指定搜索/区间搜索分页列表功能接口实例(0个评论)
    • 在go语言中实现IP/CIDR的ip和netmask互转及IP段形式互转及ip是否存在IP/CIDR(0个评论)
    • 近期评论
    • 122 在

      学历:一种延缓就业设计,生活需求下的权衡之选中评论 工作几年后,报名考研了,到现在还没认真学习备考,迷茫中。作为一名北漂互联网打工人..
    • 123 在

      Clash for Windows作者删库跑路了,github已404中评论 按理说只要你在国内,所有的流量进出都在监控范围内,不管你怎么隐藏也没用,想搞你分..
    • 原梓番博客 在

      在Laravel框架中使用模型Model分表最简单的方法中评论 好久好久都没看友情链接申请了,今天刚看,已经添加。..
    • 博主 在

      佛跳墙vpn软件不会用?上不了网?佛跳墙vpn常见问题以及解决办法中评论 @1111老铁这个不行了,可以看看近期评论的其他文章..
    • 1111 在

      佛跳墙vpn软件不会用?上不了网?佛跳墙vpn常见问题以及解决办法中评论 网站不能打开,博主百忙中能否发个APP下载链接,佛跳墙或极光..
    • 2016-10
    • 2016-11
    • 2018-04
    • 2020-03
    • 2020-04
    • 2020-05
    • 2020-06
    • 2022-01
    • 2023-07
    • 2023-10
    Top

    Copyright·© 2019 侯体宗版权所有· 粤ICP备20027696号 PHP交流群

    侯体宗的博客