scrapy-redis分布式-------处理Redis里的数据

1. 处理Redis里的数据

新浪新闻的数据爬回来了,但是放在Redis里没有处理。之前我们配置文件里面没有定制自己的ITEM_PIPELINES,而是使用了RedisPipeline,所以现在这些数据都被保存在redis的sina:items键中,所以我们需要另外做处理。
在example-project目录下可以看到一个process_items.py文件,这个文件就是scrapy-redis的example提供的从redis读取item进行处理的模版。

假设我们要把sina:items中保存的数据读出来写进MongoDB或者MySQL,那么我们可以自己写一个process_sina_profile.py文件,然后保持后台运行就可以不停地将爬回来的数据入库了。

pycharm创建数据库客户端

Redis客户端:reclient = redis.StrictRedis(host='192.168.21.53',port=6379,db=0)

Mongodb客户端:mgclient = pymongo.MongoClient(host='',port=27017)

MySQL客户端:con = pymysql.connect(host='192.168.21.53',user='root',passwd='6666',
                      db='sina',port='3306',charset='utf8')

2处理Redis里的数据存入MongoDB

启动MongoDB数据库:sudo mongod

配置文件在/etc/mongod.conf,默认端口27017

然后运行以下命令查询状态:sudo systemctl status mongodb

启动mongodb服务端:sudo service mongodb start

停止mongodb服务端:sudo service mongodb stop

重新启动mongodb:sudo service mongodb restart

使用Robmongo查看数据

再项目目录下创建 process_sina_mongodb.py文件

  #队列 FIFO模式为 blpop,栈LIFO模式为 brpop,获取键值

import json,redis, pymongo
def main():
   # 指定Redis数据库信息,端口不要加引号
   rediscli = redis.StrictRedis(host='192.168.31.114', port=6379, db=0)
   # 指定MongoDB数据库信息,端口不要加引号
   mongocli = pymongo.MongoClient(host='localhost', port=27017)
   # 创建数据库名
   db = mongocli['sina']
   # 创建表名
   sheet = db['sina_items']
   offset = 0
   while True:
      # FIFO模式为 blpop,LIFO模式为 brpop,获取键值
      source, data = rediscli.blpop(["sina:items"])
      item = json.loads(data.decode("utf-8")) #将bytes类型的数据转换成python的字典
      sheet.insert(item)
      offset += 1
      print(offset)
     #键盘终止时捕获异常
      try:
         print("Processing: %s " % item)
      except KeyError:
         print("Error procesing: %s" % item)
if __name__ == '__main__':
   main()

3、处理Redis里的数据存入 MySQL

1. 启动mysql:service mysql start
2. 登录到root用户:mysql -uroot -p
3. 显示当前的数据库:show databases
4. 创建数据库sina:create database sina;
5. 切换到指定数据库:use sina
6. 创建表sina_items以及所有字段的列名和数据类型。
7. 创建存数据表的sql:

create table sina_items(
	id int(10) auto_increment primary key  not null,
	parent_urls text,
	parent_title text,
	sub_title text,
	sub_urls text,
	sub_file_name text,
	son_urls text,
	head text,
	content text,
	crawled text,
	spider text
)charset=utf8;

执行程序从redis存入MySql的代码,执行下面程序:python3 process_sina_mysql.py

# -*- coding: utf-8 -*-
import json,redis,pymysql
def main():
    # 指定redis数据库信息
    rediscli = redis.StrictRedis(host='192.168.31.114', port = 6379, db = 0)
    # 指定mysql数据库
    mysqlcli = pymysql.connect(host='192.168.31.114', user='afu', passwd='123456', db = 'sina', port=3306, charset="utf8")

    while True:
        # FIFO模式为 blpop,LIFO模式为 brpop,获取键值
        source, data = rediscli.blpop(["sina:items"])
        item = json.loads(data.decode("utf-8"))
        try:
            # 使用cursor()方法获取操作游标
            cur = mysqlcli.cursor()
            #参数的方式传入
            params =  [item['parent_title'], item['sub_title'], item['sub_urls'], item['sub_file_name'], item['son_urls'], item['head'], item['content'], item['crawled'], item['spider']]
            # 使用execute方法执行SQL INSERT语句
            sql = "INSERT INTO sina_items(parent_title, sub_title,sub_urls,sub_file_name,son_urls,head,content,crawled ,spider) VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s )"
            cur.execute(sql,params)
            # 提交sql事务
            mysqlcli.commit()
            #关闭本次操作
            cur.close()
            print("inserted %s" % item['son_urls'])
        except pymysql.Error as e:
            print("Mysql Error %d: %s" % (e.args[0], e.args[1]))
if __name__ == '__main__':
    main()

猜你喜欢

转载自blog.csdn.net/xiaoming0018/article/details/80393019