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))

爬虫篇-python爬虫中多线程的使用的更多相关文章

  1. 【音乐爬虫】Python爬虫-selenium+browsermob-proxy 解决动态网页 js渲染问题

    1.一般的python爬虫很简单,直接请求对应网址,解析返回的数据即可,但是有很多网站的数据的js动态渲染的,你直接请求是得不到对应的数据的 这时就需要其它手段来处理了. 2.以一个例子来说明,整个过 ...

  2. 【爬虫】python爬虫

    爬虫章节 1.python如何访问互联网 URL(网页地址)+lib=>urllib 2.有问题查文档:python document. 3.response = urllib.request. ...

  3. 第七篇: python高级之多线程

    21 interest=0.05 22 count=amount+amount*interest 23 24 self.withdraw(count) 25 26 27 def transfer(_f ...

  4. python爬虫(一)_爬虫原理和数据抓取

    本篇将开始介绍Python原理,更多内容请参考:Python学习指南 为什么要做爬虫 著名的革命家.思想家.政治家.战略家.社会改革的主要领导人物马云曾经在2015年提到由IT转到DT,何谓DT,DT ...

  5. Python爬虫入门教程 50-100 Python3爬虫爬取VIP视频-Python爬虫6操作

    爬虫背景 原计划继续写一下关于手机APP的爬虫,结果发现夜神模拟器总是卡死,比较懒,不想找原因了,哈哈,所以接着写后面的博客了,从50篇开始要写几篇python爬虫的骚操作,也就是用Python3通过 ...

  6. Python爬虫教程-30-Scrapy 爬虫框架介绍

    从本篇开始学习 Scrapy 爬虫框架 Python爬虫教程-30-Scrapy 爬虫框架介绍 框架:框架就是对于相同的相似的部分,代码做到不出错,而我们就可以将注意力放到我们自己的部分了 常见爬虫框 ...

  7. python爬虫集合

    逐渐也写了有二十余篇博文,内容一多就导致有些内容不能够方便快捷定位. 虽然博客有标签进行分类,实际查找时也并不如做一个同类文章的集合来得直观. 这里就对python爬虫相关博文做个集合: 爬虫基础知识 ...

  8. Python爬虫-百度模拟登录(二)

    上一篇-Python爬虫-百度模拟登录(一) 接上一篇的继续 参数 codestring codestring jxG9506c1811b44e2fd0220153643013f7e6b1898075 ...

  9. Python爬虫编程常见问题解决方法

    Python爬虫编程常见问题解决方法: 1.通用的解决方案: [按住Ctrl键不送松],同时用鼠标点击[方法名],查看文档 2.TypeError: POST data should be bytes ...

随机推荐

  1. C++中二分法之upper_bound()、lower_bound、binary_search()函数

    前言 数组.容器vector都适用,在头文件"algorithm"中 下面的例子是针对容器的,注意返回的是距离元素3最近的指针it,输出的是*it结果为元素4,假如我想得到位置而非 ...

  2. A1083 List Grades (25 分)

    Given a list of N student records with name, ID and grade. You are supposed to sort the records with ...

  3. Linux性能优化实战学习笔记:第六讲

    一.环境准备 1.安装软件包 终端1 机器配置:2 CPU,8GB 内存 预先安装 docker.sysstat.perf等工具 [root@luoahong ~]# docker -v Docker ...

  4. [LeetCode] 212. Word Search II 词语搜索之二

    Given a 2D board and a list of words from the dictionary, find all words in the board. Each word mus ...

  5. [LeetCode] 64. Minimum Path Sum 最小路径和

    Given a m x n grid filled with non-negative numbers, find a path from top left to bottom right which ...

  6. [LeetCode] 47. Permutations II 全排列之二

    Given a collection of numbers that might contain duplicates, return all possible unique permutations ...

  7. .NET Core:跨域

    在Startup中的ConfigureServices方法中配置:services.AddCors(options => options.AddPolicy("any", b ...

  8. pytorch-04-激活函数

    sigmoid函数: 越大的负数越接近0,越大的正数越接近1缺点:(1)造成梯度消失:该函数在靠近1和0的两端,梯度几乎变成0,梯度下降法:梯度乘上学习率来更新参数,如果梯度接近0,那么没有任何信息来 ...

  9. 【layui】设置select只向下展开

    加css .layui-form-selectup dl { bottom: auto; }

  10. luogu P2495 [SDOI2011]消耗战 |虚树+LCA+dp

    题目描述 在一场战争中,战场由n个岛屿和n-1个桥梁组成,保证每两个岛屿间有且仅有一条路径可达.现在,我军已经侦查到敌军的总部在编号为1的岛屿,而且他们已经没有足够多的能源维系战斗,我军胜利在望.已知 ...