queue介绍

  • queue是python的标准库,俗称队列.可以直接import引用,在python2.x中,模块名为Queue。python3直接queue即可
  • 在python中,多个线程之间的数据是共享的,多个线程进行数据交换的时候,不能够保证数据的安全性和一致性,所以当多个线程需要进行数据交换的时候,队列就出现了,队列可以完美解决线程间的数据交换,保证线程间数据的安全性和一致性。

#多线程实战栗子(糗百)
#用一个队列Queue对象,
#先产生所有url,put进队列;
#开启多线程,把queue队列作为参数传入
#主函数中读取url import requests
from queue import Queue
import re,os,threading,time
# 构造所有ip地址并添加进queue队列
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/65.0.3325.181 Safari/537.36'
}
urlQueue = Queue()
[urlQueue.put('http://www.qiumeimei.com/image/page/{}'.format(i)) for i in range(1,14)]
def get_image(urlQueue): while True:
try:
# 不阻塞的读取队列数据
url = urlQueue.get_nowait()
# i = urlQueue.qsize()
except Exception as e:
break
print('Current Thread Name %s, Url: %s ' % (threading.currentThread().name, url))
try:
res = requests.get(url, headers=headers)
url_infos = re.findall('data-lazy-src="(.*?)"', res.text, re.S)
for url_info in url_infos:
if os.path.exists(img_path + url_info[-20:]):
print('图片已存在')
else:
image = requests.get(url_info, headers=headers)
with open(img_path + url_info[-20:], 'wb') as fp:
time.sleep(1)
fp.write(image.content)
print('正在下载:' + url_info)
except Exception as e:
print(e) if __name__ == '__main__':
startTime = time.time()
# 定义图片存储路径
img_path = './img/'
if not os.path.exists(img_path):
os.mkdir(img_path)
threads = []
# 可以调节线程数, 进而控制抓取速度
threadNum = 4
for i in range(0, threadNum):
t = threading.Thread(target=get_image, args=(urlQueue,))
threads.append(t)
for t in threads:
t.start()
for t in threads:
# 多线程多join的情况下,依次执行各线程的join方法, 这样可以确保主线程最后退出, 且各个线程间没有阻塞
t.join()
endTime = time.time()
print('Done, Time cost: %s ' % (endTime - startTime))

最新文章

  1. 深入.NET平台的软件系统分成开发(1/6)
  2. 十三. JEB破解三
  3. 使用spring等框架的web程序在Tomcat下的启动顺序及思路理清
  4. 383. Ransom Note
  5. POJ - 1159 Palindrome(dp-回文变形)
  6. IOSアプリケーション開発環境の構築
  7. c# 预处理命令
  8. windows下重命名一个带有前缀"."dot字符的名字的错误问题
  9. httppost body的实现, 和body是gb2312等编码的实现
  10. MVC扩展ModelBinder使类型为DateTime的Action参数可以接收日期格式的字符串
  11. C语言两个libxml2库使用的问题
  12. phpcms笔记
  13. 【洛谷P1134 阶乘问题】
  14. WebForm文件上传
  15. 乘法器的Verilog HDL实现(转载)
  16. Java多线程面试题整理
  17. com.fasterxml.jackson.databind.exc.InvalidDefinitionException: No serializer found for class cn.edu.
  18. 创建多线程Thread
  19. [No0000C0]百度网盘真实地址解析(不用下载百度网盘)20170301
  20. Unity 灯光系统详解

热门文章

  1. linux下找到JVM占用资源最高的线程
  2. NLP中一些数学知识
  3. 基于DFA算法、RegExp对象和vee-validate实现前端敏感词过滤
  4. Educational Codeforces Round 70 题解
  5. MySQL实战45讲学习笔记:第二十八讲
  6. pymongo方法详解
  7. oracle--表空间基本操作
  8. docker-compose之跳板机jumpserver部署
  9. Python学习笔记系列
  10. 大话设计模式Python实现-策略模式