7.4 scrapy - 레디 스 리얼 - 레디 스의 데이터 처리
레디 스의 데이터 처리
데이터 네트워크는 다시 상승 운명, 그러나 레디 스에는 치료가 없다. 우리가 또 다른 거래를 할 필요가 있으므로, 항목 키 : 우리가 전에, 이제 이러한 데이터는 youyuan의 레디 스에 저장되어있는 자신의 ITEM_PIPELINES을 사용자 정의 할 구성 파일,하지만 RedisPipeline의 사용이 없습니다.
볼 수 있습니다 scrapy-youyuan 디렉토리에서 process_items.py
파일을, 파일은 레디 스에서 스텐실 항목을 수행 독서 과정에 의해 제공되는 예를 scrapy이 - 레디 스입니다.
우리가 youyuan한다고 가정 : 항목 MongoDB를 작성 또는 MySQL은, 우리가 자신의 쓸 수에 저장된 데이터를 읽어 process_youyuan_profile.py
파일을 다음 백그라운드에서 실행 유지는 데이터웨어 하우징 백업 크롤링을 유지할 수있다.
MongoDB를 저장
- MongoDB의 데이터베이스를 시작합니다 :
sudo mongod
- 다음 절차를 수행합니다 :
py2 process_youyuan_mongodb.py
# process_youyuan_mongodb.py
# -*- coding: utf-8 -*-
import json
import redis
import pymongo
def main():
# 指定Redis数据库信息
rediscli = redis.StrictRedis(host='192.168.199.108', port=6379, db=0)
# 指定MongoDB数据库信息
mongocli = pymongo.MongoClient(host='localhost', port=27017)
# 创建数据库名
db = mongocli['youyuan']
# 创建表名
sheet = db['beijing_18_25']
while True:
# FIFO模式为 blpop,LIFO模式为 brpop,获取键值
source, data = rediscli.blpop(["youyuan:items"])
item = json.loads(data)
sheet.insert(item)
try:
print u"Processing: %(name)s <%(link)s>" % item
except KeyError:
print u"Error procesing: %r" % item
if __name__ == '__main__':
main()
MySQL의에 저장
-
시작 MySQL의 :
mysql.server start
(더 많은 플랫폼이 동일하지 않습니다) -
루트 사용자로 로그인 :
mysql -uroot -p
-
데이터베이스를 작성
youyuan
:create database youyuan;
-
지정된 데이터베이스로 전환 :
use youyuan
-
테이블 만들기
beijing_18_25
모든 필드 및 데이터 유형 및 열 이름을. -
다음 절차를 수행합니다 :
py2 process_youyuan_mysql.py
#process_youyuan_mysql.py
# -*- coding: utf-8 -*-
import json
import redis
import MySQLdb
def main():
# 指定redis数据库信息
rediscli = redis.StrictRedis(host='192.168.199.108', port = 6379, db = 0)
# 指定mysql数据库
mysqlcli = MySQLdb.connect(host='127.0.0.1', user='power', passwd='xxxxxxx', db = 'youyuan', port=3306, use_unicode=True)
while True:
# FIFO模式为 blpop,LIFO模式为 brpop,获取键值
source, data = rediscli.blpop(["youyuan:items"])
item = json.loads(data)
try:
# 使用cursor()方法获取操作游标
cur = mysqlcli.cursor()
# 使用execute方法执行SQL INSERT语句
cur.execute("INSERT INTO beijing_18_25 (username, crawled, age, spider, header_url, source, pic_urls, monologue, source_url) VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s )", [item['username'], item['crawled'], item['age'], item['spider'], item['header_url'], item['source'], item['pic_urls'], item['monologue'], item['source_url']])
# 提交sql事务
mysqlcli.commit()
#关闭本次操作
cur.close()
print "inserted %s" % item['source_url']
except MySQLdb.Error,e:
print "Mysql Error %d: %s" % (e.args[0], e.args[1])
if __name__ == '__main__':
main()