scrapy整合hbase爬取資料並存入hbase
阿新 • • 發佈:2019-02-14
在網上看了大篇的帖子都是關於scrapy與mongodb、mysql、redis等整合的文章,唯獨沒有看到scrapy與hbase整合的文章。今天動手實驗了一下,整理成本篇博文,分享給大家。
scrapy爬取資料的例子網上很多,本人在此就不再贅訴了。
此處只著重描寫scrapy如何入庫至hbase。
本文主要通過HappyBase操作hbase。
HappyBase 是 FaceBook 員工開發的操作 HBase 的 Python 庫,其基於 Python Thrift,但使用方式比 Thrift 簡單、簡潔許多,已被廣泛應用。
1、安裝happybase
pip install happybase
2、啟動hbase thrift服務
nohup hbase thrift -p 9090 start &
3、在scrapy專案下setting.py檔案中定義HBASE_HOST 和HBASE_TABLE
HBASE_HOST = '192.168.22.15'
HBASE_TABLE = 'novel'
4、在pipelines.py中編寫Hbase入庫的Pipeline
class NovelHBasePipeline(object):
def __init__(self):
host = settings['HBASE_HOST' ]
table_name = settings['HBASE_TABLE']
connection = happybase.Connection(host)
table = connection.table(table_name)
self.table = table
def process_item(self, item, spider):
bookName = item['bookName']
bookTitle = item['bookTitle']
chapterURL = item['chapterURL' ]
self.table.put(md5(bookName + bookTitle).hexdigest(),
{'cf1:bookname': bookName, 'cf1:booktitle': bookTitle, 'cf1:chapterurl': chapterURL})
return item
5、在setting.py檔案中配置編寫的Pipeline
ITEM_PIPELINES = {
'novelspider.pipelines.NovelspiderPipeline': 500,
'novelspider.pipelines.NovelHBasePipeline': 1
}
至此,所有的整合工作已經完成,即可執行您的spider爬取資料並存至hbase。