安装

1.tomorrow安装,用pip可以直接安装

pip install tomorrow

单线程

1。以下案例是单线程时候跑的情况,在下载图片的时候很耗时。

# coding:utf-8
from bs4 import BeautifulSoup
import requests
import os
import time # 当前脚本所在的目录
cur_path = os.path.dirname(os.path.realpath(__file__)) def get_img_urls():
r = requests.get("http://699pic.com/sousuo-218808-13-1.html")
fengjing = r.content
soup = BeautifulSoup(fengjing, "html.parser")
# 找出所有的标签
images = soup.find_all(class_="lazy")
return images def save_img(imgUrl):
try:
jpg_rl = imgUrl["data-original"]
title = imgUrl["title"]
# print(title)
# print(jpg_rl)
# print("")
# 判断是否有jpg文件夹,不存在创建一个
save_file = os.path.join(cur_path, "jpg")
if not os.path.exists(save_file): os.makedirs(save_file) with open(os.path.join(save_file, title+'.jpg'), "wb") as f:
f.write(requests.get(jpg_rl).content)
except:
pass if __name__ == "__main__":
t1 = time.time() image_ulrs = get_img_urls()
for i in image_ulrs:
save_img(i) t2 = time.time()
print("总耗时:%.2f 秒"%(t2-t1))

运行结果:

耗时:4.27 秒

使用多线程tomorrow

1.一行代码搞定多线程,在函数上加个@threads(5),括号里面代码线程的数量,数字越大,运行的速度越快

# coding:utf-8
from bs4 import BeautifulSoup
import requests
import os
import time
from tomorrow import threads # 当前脚本所在的目录
cur_path = os.path.dirname(os.path.realpath(__file__)) def get_img_urls():
r = requests.get("http://699pic.com/sousuo-218808-13-1.html")
fengjing = r.content
soup = BeautifulSoup(fengjing, "html.parser")
# 找出所有的标签
images = soup.find_all(class_="lazy")
return images @threads(5)
def save_img(imgUrl):
try:
jpg_rl = imgUrl["data-original"]
title = imgUrl["title"]
# print(title)
# print(jpg_rl)
# print("")
# 判断是否有jpg文件夹,不存在创建一个
save_file = os.path.join(cur_path, "jpg")
if not os.path.exists(save_file): os.makedirs(save_file) with open(os.path.join(save_file, title+'.jpg'), "wb") as f:
f.write(requests.get(jpg_rl).content)
except:
pass if __name__ == "__main__":
t1 = time.time() image_ulrs = get_img_urls()
for i in image_ulrs:
save_img(i) t2 = time.time()
print("总耗时:%.2f 秒"%(t2-t1))

运行结果:

总耗时:0.24 秒

参考github案例:Tomorrow

python自动化交流 QQ群:779429633

最新文章

  1. 什么时候用Model,什么时候用Entity?[转载知乎-备忘]
  2. [转] VB之Val()函数的使用
  3. imx6dl i2c4 support
  4. 漫水填充算法 - cvFloodFill() 实现
  5. PHP获得两个绝对路径的相对路径
  6. Mysql binlog日志解析
  7. iOS Size Class使用
  8. DOM操作中,getElementByXXXX 和 querySelector 的区别
  9. php实现点击文字提交表单并传递数据至下一个页面
  10. 21 re正则模块 垃圾回收机制
  11. C# 通过 Quartz .NET 实现 schedule job 的处理
  12. UBUNTU 16.04 安装AVD "An error occurred while running "android create avd
  13. vs2012升级vs2017后的一些坑
  14. Java,mysql String与date类型转换
  15. [No0000152]C#基础之IL,轻松读懂IL
  16. rc.d/rc.local 自动启 tomcat 启不来
  17. Java课程设计—拿火柴小游戏
  18. 在浏览器外打开PDF文档
  19. javascript事件处理程序的3个阶段
  20. 170518、FastDFS_配置文件详解

热门文章

  1. .net设置浏览器的文本模式
  2. vue页面高度填充,不出现滚动条
  3. linux命令(43):cal命令
  4. 【hdoj_2079】选课时间(母函数)
  5. 网站页面SEO的三个标签怎么写有利【转载】
  6. KVM-克隆和快照管理
  7. C# For Bot Framework
  8. Struts2 简单的上传文件并且显示图片
  9. CodeForces 779C Dishonest Sellers
  10. Flask实战第67天:Flask+Celery实现邮件和短信异步发送