梦想橡皮擦 2019-04-22 14:30:22 浏览 156 评论 0
编程语言
python
分布式
线程
Image
exception
多线程
thread
摘要: 1. 图虫网多线程爬取 - 写在前面 经历了一顿噼里啪啦的操作之后, 终于我把博客写到了第 10 篇, 后面, 慢慢的会涉及到更多的爬虫模块, 有人问 scrapy 啥时候开始用, 这个我预计要在 30 篇以后了吧, 后面的套路依旧慢节奏的, 所以莫着急了, 100 篇呢, 预计 4~5 个月写完, 常见的反反爬后面也会写的, 还有 fuck login 类的内容.
1. 图虫网多线程爬取 - 写在前面
经历了一顿噼里啪啦的操作之后, 终于我把博客写到了第 10 篇, 后面, 慢慢的会涉及到更多的爬虫模块, 有人问 scrapy 啥时候开始用, 这个我预计要在 30 篇以后了吧, 后面的套路依旧慢节奏的, 所以莫着急了, 100 篇呢, 预计 4~5 个月写完, 常见的反反爬后面也会写的, 还有 fuck login 类的内容.
2. 图虫网多线程爬取 - 爬取图虫网
为什么要爬取这个网站, 不知道哎~ 莫名奇妙的收到了, 感觉图片质量不错, 不是那些妖艳贱货 可以比的, 所以就开始爬了, 搜了一下网上有人也在爬, 但是基本都是 py2,py3 的还没有人写, 所以顺手写一篇吧.
3. 图虫网多线程爬取 - 起始页面
https://tuchong.com/explore/
这个页面中有很多的标签, 每个标签下面都有很多图片, 为了和谐, 我选择了一个非常好的标签花卉 你可以选择其他的, 甚至, 你可以把所有的都爬取下来.
https://tuchong.com/tags/花卉/ # 花卉编码成了 花卉 这个无所谓
我们这次也玩点以前没写过的, 使用 python 中的 queue, 也就是队列
下面是我从别人那顺来的一些解释, 基本爬虫初期也就用到这么多
1. 初始化: class Queue.Queue(maxsize) FIFO 先进先出
2. 包中的常用方法:
- queue.qsize() 返回队列的大小
- queue.empty() 如果队列为空, 返回 True, 反之 False
- queue.full() 如果队列满了, 返回 True, 反之 False
- queue.full 与 maxsize 大小对应
- queue.get([block[, timeout]]) 获取队列, timeout 等待时间
3. 创建一个 "队列" 对象
- import queue
- myqueue = queue.Queue(maxsize = 10)
4. 将一个值放入队列中
myqueue.put(10)
5. 将一个值从队列中取出
myqueue.get()
4. 图虫网多线程爬取 - 开始编码
首先我们先实现主要方法的框架, 我依旧是把一些核心的点, 都写在注释上面
- def main():
- # 声明一个队列, 使用循环在里面存入 100 个页码
- page_queue = Queue(100)
- for i in range(1,101):
- page_queue.put(i)
- # 采集结果 (等待下载的图片地址)
- data_queue = Queue()
- # 记录线程的列表
- thread_crawl = []
- # 每次开启 4 个线程
- craw_list = ['采集线程 1 号','采集线程 2 号','采集线程 3 号','采集线程 4 号']
- for thread_name in craw_list:
- c_thread = ThreadCrawl(thread_name, page_queue, data_queue)
- c_thread.start()
- thread_crawl.append(c_thread)
- # 等待 page_queue 队列为空, 也就是等待之前的操作执行完毕
- while not page_queue.empty():
- pass
- if __name__ == '__main__':
- main()
代码运行之后, 成功启动了 4 个线程, 然后等待线程结束, 这个地方注意, 你需要把 ThreadCrawl 类补充完整
- class ThreadCrawl(threading.Thread):
- def __init__(self, thread_name, page_queue, data_queue):
- # threading.Thread.__init__(self)
- # 调用父类初始化方法
- super(ThreadCrawl, self).__init__()
- self.threadName = thread_name
- self.page_queue = page_queue
- self.data_queue = data_queue
- def run(self):
- print(self.threadName + '启动 ************')
运行结果
线程已经开启, 在 run 方法中, 补充爬取数据的代码就好了, 这个地方引入一个全局变量, 用来标识爬取状态
CRAWL_EXIT = False
先在 main 方法中加入如下代码
- CRAWL_EXIT = False # 这个变量声明在这个位置
- class ThreadCrawl(threading.Thread):
- def __init__(self, thread_name, page_queue, data_queue):
- # threading.Thread.__init__(self)
- # 调用父类初始化方法
- super(ThreadCrawl, self).__init__()
- self.threadName = thread_name
- self.page_queue = page_queue
- self.data_queue = data_queue
- def run(self):
- print(self.threadName + '启动 ************')
- while not CRAWL_EXIT:
- try:
- global tag, url, headers,img_format # 把全局的值拿过来
- # 队列为空 产生异常
- page = self.page_queue.get(block=False) # 从里面获取值
- spider_url = url_format.format(tag,page,100) # 拼接要爬取的 URL
- print(spider_url)
- except:
- break
- timeout = 4 # 合格地方是尝试获取 3 次, 3 次都失败, 就跳出
- while timeout> 0:
- timeout -= 1
- try:
- with requests.Session() as s:
- response = s.get(spider_url, headers=headers, timeout=3)
- json_data = response.JSON()
- if json_data is not None:
- imgs = json_data["postList"]
- for i in imgs:
- imgs = i["images"]
- for img in imgs:
- img = img_format.format(img["user_id"],img["img_id"])
- self.data_queue.put(img) # 捕获到图片链接, 之后, 存入一个新的队列里面, 等待下一步的操作
- break
- except Exception as e:
- print(e)
- if timeout <= 0:
- print('time out!')
- def main():
- # 代码在上面
- # 等待 page_queue 队列为空, 也就是等待之前的操作执行完毕
- while not page_queue.empty():
- pass
- # 如果 page_queue 为空, 采集线程退出循环
- global CRAWL_EXIT
- CRAWL_EXIT = True
- # 测试一下队列里面是否有值
- print(data_queue)
经过测试, data_queue 里面有数据啦!!, 哈哈, 下面在使用相同的操作, 去下载图片就好喽
完善 main 方法
- def main():
- # 代码在上面
- for thread in thread_crawl:
- thread.join()
- print("抓取线程结束")
- thread_image = []
- image_list = ['下载线程 1 号', '下载线程 2 号', '下载线程 3 号', '下载线程 4 号']
- for thread_name in image_list:
- Ithread = ThreadDown(thread_name, data_queue)
- Ithread.start()
- thread_image.append(Ithread)
- while not data_queue.empty():
- pass
- global DOWN_EXIT
- DOWN_EXIT = True
- for thread in thread_image:
- thread.join()
- print("下载线程结束")
还是补充一个 ThreadDown 类, 这个类就是用来下载图片的.
- class ThreadDown(threading.Thread):
- def __init__(self, thread_name, data_queue):
- super(ThreadDown, self).__init__()
- self.thread_name = thread_name
- self.data_queue = data_queue
- def run(self):
- print(self.thread_name + '启动 ************')
- while not DOWN_EXIT:
- try:
- img_link = self.data_queue.get(block=False)
- self.write_image(img_link)
- except Exception as e:
- pass
- def write_image(self, url):
- with requests.Session() as s:
- response = s.get(url, timeout=3)
- img = response.content # 获取二进制流
- try:
- file = open('image/' + str(time.time())+'.jpg', 'wb')
- file.write(img)
- file.close()
- print('image/' + str(time.time())+'.jpg 图片下载完毕')
- except Exception as e:
- print(e)
- return
运行之后, 等待图片下载就可以啦~~
关键注释已经添加到代码里面了, 收图吧 (ᴗ), 这次代码回头在上传到 GitHub 上 因为比较简单
她专科学历
27 岁从零开始学习 c,c++,python 编程语言
29 岁编写百例教程
30 岁掌握 10 种编程语言,
用自学的经历告诉你, 学编程就找梦想橡皮擦
来源: https://yq.aliyun.com/articles/699316