Python爬虫开发【第1篇】【多线程爬虫及案例】
糗事百科爬虫实例:
地址:http://www.qiushibaike.com/8hr/page/1
需求:
使用requests获取页面信息,用XPath / re 做数据提取
获取每个帖子里的
用户头像链接、用户姓名、段子内容、点赞次数和评论次数保存到 json 文件内
#qiushibaike.py #import urllib
#import re
#import chardet import requests
from lxml import etree page = 1
url = 'http://www.qiushibaike.com/8hr/page/' + str(page)
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/52.0.2743.116 Safari/537.36',
'Accept-Language': 'zh-CN,zh;q=0.8'} try:
response = requests.get(url, headers=headers)
resHtml = response.text html = etree.HTML(resHtml)
result = html.xpath('//div[contains(@id,"qiushi_tag")]') for site in result:
item = {} imgUrl = site.xpath('./div/a/img/@src')[0].encode('utf-8')
username = site.xpath('./div/a/@title')[0].encode('utf-8')
#username = site.xpath('.//h2')[0].text
content = site.xpath('.//div[@class="content"]/span')[0].text.strip().encode('utf-8')
# 投票次数
vote = site.xpath('.//i')[0].text
#print site.xpath('.//*[@class="number"]')[0].text
# 评论信息
comments = site.xpath('.//i')[1].text print imgUrl, username, content, vote, comments except Exception, e:
print e
Queue(队列对象)
Queue是python中的标准库,可以直接import Queue引用;队列是线程间最常用的交换数据的形式
python下多线程的思考
对于资源,加锁是个重要的环节。因为python原生的list,dict等,都是not thread safe的。而Queue,是线程安全的,因此在满足使用条件下,建议使用队列
初始化: class Queue.Queue(maxsize) FIFO 先进先出
包中的常用方法:
Queue.qsize() 返回队列的大小
Queue.empty() 如果队列为空,返回True,反之False
Queue.full() 如果队列满了,返回True,反之False
Queue.full 与 maxsize 大小对应
Queue.get([block[, timeout]])获取队列,timeout等待时间
创建一个“队列”对象
- import Queue
- myqueue = Queue.Queue(maxsize = 10)
将一个值放入队列中
- myqueue.put(10)
将一个值从队列中取出
- myqueue.get()
多线程爬虫示意图:

# -*- coding:utf-8 -*-
import requests
from lxml import etree
from Queue import Queue
import threading
import time
import json class thread_crawl(threading.Thread):
'''
抓取线程类
''' def __init__(self, threadID, q):
threading.Thread.__init__(self)
self.threadID = threadID
self.q = q def run(self):
print "Starting " + self.threadID
self.qiushi_spider()
print "Exiting ", self.threadID def qiushi_spider(self):
# page = 1
while True:
if self.q.empty():
break
else:
page = self.q.get()
print 'qiushi_spider=', self.threadID, ',page=', str(page)
url = 'http://www.qiushibaike.com/8hr/page/' + str(page) + '/'
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/52.0.2743.116 Safari/537.36',
'Accept-Language': 'zh-CN,zh;q=0.8'}
# 多次尝试失败结束、防止死循环
timeout = 4
while timeout > 0:
timeout -= 1
try:
content = requests.get(url, headers=headers)
data_queue.put(content.text)
break
except Exception, e:
print 'qiushi_spider', e
if timeout < 0:
print 'timeout', url class Thread_Parser(threading.Thread):
'''
页面解析类;
''' def __init__(self, threadID, queue, lock, f):
threading.Thread.__init__(self)
self.threadID = threadID
self.queue = queue
self.lock = lock
self.f = f def run(self):
print 'starting ', self.threadID
global total, exitFlag_Parser
while not exitFlag_Parser:
try:
'''
调用队列对象的get()方法从队头删除并返回一个项目。可选参数为block,默认为True。
如果队列为空且block为True,get()就使调用线程暂停,直至有项目可用。
如果队列为空且block为False,队列将引发Empty异常。
'''
item = self.queue.get(False)
if not item:
pass
self.parse_data(item)
self.queue.task_done()
print 'Thread_Parser=', self.threadID, ',total=', total
except:
pass
print 'Exiting ', self.threadID def parse_data(self, item):
'''
解析网页函数
:param item: 网页内容
:return:
'''
global total
try:
html = etree.HTML(item)
result = html.xpath('//div[contains(@id,"qiushi_tag")]')
for site in result:
try:
imgUrl = site.xpath('.//img/@src')[0]
title = site.xpath('.//h2')[0].text
content = site.xpath('.//div[@class="content"]/span')[0].text.strip()
vote = None
comments = None
try:
vote = site.xpath('.//i')[0].text
comments = site.xpath('.//i')[1].text
except:
pass
result = {
'imgUrl': imgUrl,
'title': title,
'content': content,
'vote': vote,
'comments': comments,
} with self.lock:
# print 'write %s' % json.dumps(result)
self.f.write(json.dumps(result, ensure_ascii=False).encode('utf-8') + "\n") except Exception, e:
print 'site in result', e
except Exception, e:
print 'parse_data', e
with self.lock:
total += 1 data_queue = Queue()
exitFlag_Parser = False
lock = threading.Lock()
total = 0 def main():
output = open('qiushibaike.json', 'a') #初始化网页页码page从1-10个页面
pageQueue = Queue(50)
for page in range(1, 11):
pageQueue.put(page) #初始化采集线程
crawlthreads = []
crawlList = ["crawl-1", "crawl-2", "crawl-3"] for threadID in crawlList:
thread = thread_crawl(threadID, pageQueue)
thread.start()
crawlthreads.append(thread) #初始化解析线程parserList
parserthreads = []
parserList = ["parser-1", "parser-2", "parser-3"]
#分别启动parserList
for threadID in parserList:
thread = Thread_Parser(threadID, data_queue, lock, output)
thread.start()
parserthreads.append(thread) # 等待队列清空
while not pageQueue.empty():
pass # 等待所有线程完成
for t in crawlthreads:
t.join() while not data_queue.empty():
pass
# 通知线程是时候退出
global exitFlag_Parser
exitFlag_Parser = True for t in parserthreads:
t.join()
print "Exiting Main Thread"
with lock:
output.close() if __name__ == '__main__':
main()
Python爬虫开发【第1篇】【多线程爬虫及案例】的更多相关文章
- python自动化开发-[第二十三天]-初识爬虫
今日概要: 1.爬汽车之家的新闻资讯 2.爬github和chouti 3.requests和beautifulsoup 4.轮询和长轮询 5.django request.POST和request. ...
- 【Python之路】特别篇--多线程与多进程
并发 与 并行 的区别: 解释一:并发是在同一实体上的多个事件,并行是在不同实体上的多个事件: 解释二:并发是指两个或多个事件在同一时间间隔发生,而并行是指两个或者多个事件在同一时刻发生. 并发:就是 ...
- python测试开发django-51.Ajax发送post请求登录案例
前言 我想实现一个登录功能:登录的接口是另外一个地方提供,页面上点登录按钮的时候,先访问登录接口,根据接口返回json信息判断是否登录成功,登录成功页面跳转,登录不成功,在登录首页显示失败原因 登录页 ...
- Python爬虫开发【第1篇】【Scrapy框架】
Scrapy 框架介绍 Scrapy是用纯Python实现一个为了爬取网站数据.提取结构性数据而编写的应用框架. Srapy框架,用户只需要定制开发几个模块就可以轻松的实现一个爬虫,用来抓取网页内容以 ...
- Python爬虫开发【第1篇】【Scrapy入门】
Scrapy的安装介绍 Scrapy框架官方网址:http://doc.scrapy.org/en/latest Scrapy中文维护站点:http://scrapy-chs.readthedocs. ...
- Python爬虫开发【第1篇】【urllib2】
1.urlopen # urllib2_urlopen.py # 导入urllib2 库 import urllib2 # 向指定的url发送请求,并返回服务器响应的类文件对象,urlopen中有da ...
- 爬虫开发python工具包介绍 (1)
本文来自网易云社区 作者:王涛 本文大纲: 简易介绍今天要讲解的两个爬虫开发的python库 详细介绍 requests库及函数中的各个参数 详细介绍 tornado 中的httpcilent的应用 ...
- Python爬虫开发与项目实战
Python爬虫开发与项目实战(高清版)PDF 百度网盘 链接:https://pan.baidu.com/s/1MFexF6S4No_FtC5U2GCKqQ 提取码:gtz1 复制这段内容后打开百度 ...
- Python爬虫开发与项目实战pdf电子书|网盘链接带提取码直接提取|
Python爬虫开发与项目实战从基本的爬虫原理开始讲解,通过介绍Pthyon编程语言与HTML基础知识引领读者入门,之后根据当前风起云涌的云计算.大数据热潮,重点讲述了云计算的相关内容及其在爬虫中的应 ...
随机推荐
- ubuntu18.04 server配置静态ip
最新发布的ubuntu18.04 server,启用了新的网络工具netplan,对于命令行配置网络参数跟之前的版本有比较大的差别,现在介绍如下:1.其网络配置文件是放在/etc/netplan/50 ...
- svn基本使用详情
1.增加(Add)先提到变更列表中,再commit到配置库中,选择新增文件,右键SVN菜单执行“Add“操作提交到”变更列表中”,然后右键SVN菜单执行”SVNCommit”提交到版本库中. 2.删除 ...
- STM32开发环境--使用MDK建立一个工程
STM32开发环境--使用MDK建立一个工程 该工程模版是基于库函数基础制作而成,其中有借鉴相关资料.虽然工程模版一旦建立,以后任何项目只需套用即可,但考虑到长时间不使用,在将来某天可能会突然用到,再 ...
- ASP.NET MVC如何在页面加载完成后ajax异步刷新
背景:之前已写过两篇有关Ajax的随笔,这一篇是单独针对在页面加载完成的Ajax操作.比如说打开学生列表页面,先加载页面,然后以Ajax的方式,从数据库中检索相应的学生信息,给浏览者更好的体验. 简单 ...
- tcpcopy简单用法
这篇文章介绍下网易开源的流量重放(replay)工具TCPCopy,说是简单介绍,绝对不是谦虚,因为自己了解的确实也不多.为什么不甚了解呢,大家可以到TCPCopy的官方仓库看看,https://gi ...
- Jmeter接口测试-正则表达式提取器-提取token
在使用Jmeter过程中会有这样的场景, A接口执行后返回json字符串, 这个json中有B接口需要的某一个参数, 那如何来实现呢? 第一步:添加正则表达式 方法非常简单, 这就是我们今天要讲的正则 ...
- HDU-1061-Rightmost Digit,快速幂水过!~~
Rightmost Digit Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others) ...
- 七牛云 X 英语流利说:教育 3.0 时代的智能突破
美国当地时间 2018 年 9 月 27 日,国内领先的人工智能驱动的教育科技公司「英语流利说」正式挂牌纽交所,以其独创的教育 3.0 模式,成为中国「AI+ 教育」第一股. 教育 3.0 时代的智能 ...
- 洛谷P1521 求逆序对 题解
题意: 求1到n的全排列中有m对逆序对的方案数. 思路: 1.f[i][j]表示1到i的全排列中有j对逆序对的方案数. 2.显然,1到i的全排列最多有(i-1)*i/2对逆序对,而对于f[i][j]来 ...
- [codevs3622] 假期(单调队列)
传送门 首先考虑暴力做法,可以先求一遍前缀和 sum,然后ans = max(ans, sum[i] - sum[k]) (i - q <= k <= i - p) 但这个肯定会超时. 仔 ...