您的位置:首页 > 其它

使用scrapy 0.24 制作的小说爬虫

2015-01-16 13:18 405 查看
摘要: 使用scrapy 0.24 制作的小说爬虫,并配置采集频率,采集间隔

使用scrapy制作的小说爬虫

爬虫配套的django网站 https://www.zybuluo.com/xuemy268/note/63660

首先是安装scrapy,在Windows下的安装比较麻烦,大家好好百度下,这里就不细说了,在ubuntu下的安装

apt-get install python-dev
apt-get install python-lxml
apt-get install libffi-dev
pip install scrapy

爬取小说的话无非就是爬取两个页面,小说介绍页和小说章节页,然后又分为2种情况

小说介绍页中含有章节列表目录

小说介绍页中不含章节列表目录,但是含有指向章节列表的URL

相对于a情况来说:

def parse(self,response):
# 使用xpath,获取小说名,作者,分类,介绍,章节列表URL
#使用下面的方法获取章节列表URL可以直接使用Request(),还能直接获得章节名
#http://www.ydzww.com
SgmlLinkExtractor(restrict_xpaths=(config.get("NovelChapterList_XPATH"),),).extract_links(response)

对于b情况:

#可以使用xpath 获取 指向章节列表的URL,如何url不完整的话可以使用
get_base_url(response) 获取域名信息,然后使用moves.urllib.parse.urljoin()进行拼接
#然后就可以使用Request(),后面的步奏基本上就和a情况一样了
#http://www.ydzww.com

插入数据库这个方面,google一下,使用twisted的数据库接口,好像这个是异步的,配合scrapy估计会更好,要是使用别的也没有关系,我用的django Model 没发现问题

提供一个网上搜出来的代码

# Cannot use this to create the table, must have table already created

from twisted.enterprise import adbapi
import datetime
import MySQLdb.cursors

class SQLStorePipeline(object):

def __init__(self):
self.dbpool = adbapi.ConnectionPool('MySQLdb', db='mydb',
user='myuser', passwd='mypass', cursorclass=MySQLdb.cursors.DictCursor,
charset='utf8', use_unicode=True)

def process_item(self, item, spider):
# run db query in thread pool
query = self.dbpool.runInteraction(self._conditional_insert, item)
query.addErrback(self.handle_error)

return item

def _conditional_insert(self, tx, item):
# create record if doesn't exist.
# all this block run on it's own thread
tx.execute("select * from websites where link = %s", (item['link'][0], ))
result = tx.fetchone()
if result:
log.msg("Item already stored in db: %s" % item, level=log.DEBUG)
else:
tx.execute(\
"insert into websites (link, created) "
"values (%s, %s)",
(item['link'][0],
datetime.datetime.now())
)
log.msg("Item stored in db: %s" % item, level=log.DEBUG)

def handle_error(self, e):
log.err(e)

#该代码片段来自于: http://www.sharejs.com/codes/python/8392 #http://www.ydzww.com


另外就是爬虫控制这块,使用默认的控制,爬虫爬的太快了,有封站的危险,再有就是怕那么快,把采集站爬掉了,以后采集谁的呀?

# 同时下载个数
CONCURRENT_REQUESTS = 5
CONCURRENT_REQUESTS_PER_SPIDER = 5
CLOSESPIDER_PAGECOUNT = 100000
CLOSESPIDER_TIMEOUT = 36000
DOWNLOAD_DELAY = 1.5
RETRY_ENABLED = False
COOKIES_ENABLED = False
# http://www.ydzww.com[/code] 这个是我的配置,从我这么多天的采集来看,一分钟采集40个左右的页面,也差不多了

内容的过滤

基本上内容都是用xpath来获取的,然后章节内容也里面还使用了一些正则,去除内容里面的URL,还有一些有关采集站的信息

(http(s)?://.)?(www\.)?[-a-zA-Z0-9@:!$^&\*%.()_\+~#=\uff10-\uff40{}\[\]]{2,256}[\[\]{}!$^\*&@:%._\+~#=()][\[\]{}a-z!$^\*&@:%._\uff10-\uff40\s]{2,6}\b([\[\]-a-zA-Z0-9()@:%_\+.~#?&//=]*)
# www.ydzww.com

这个是我使用来处理内容页url的正则,到目前为止采集小说里面没有碰到处理不了的URL,要是大家能发现有处理不了的话,评论一下,我好做个修改,方便大家使用么!

爬虫比现行的小说爬虫来说,优点有以下几点:

能在linux下面完美运行,windows下面能运行,但是有时可能出现log文件乱码

通过和数据库的配置,一本小说对应一个采集站,3分钟循环监控单本小说,保证小说能够在最快的时间采集

运行快速稳定,scrapy的稳定性还是值得肯定的

已经用这个爬虫程序制作了一个小说站, 易读中文网
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息