分布式爬虫怎么处理Redis里的数据

发布时间:2021-09-02 14:50:03 作者:chen
来源:亿速云 阅读:108

这篇文章主要讲解了“分布式爬虫怎么处理Redis里的数据”,文中的讲解内容简单清晰,易于学习与理解,下面请大家跟着小编的思路慢慢深入,一起来研究和学习“分布式爬虫怎么处理Redis里的数据”吧!

存入MongoDB

1.启动MongoDB数据库:sudo mongod

2.执行下面程序: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()

分布式爬虫怎么处理Redis里的数据

存入 MySQL

1.启动mysql:mysql.server start(更平台不一样)

2.登录到root用户:mysql -uroot -p

3.创建数据库youyuan:create database youyuan;

4.切换到指定数据库:use youyuan

5.创建表beijing_18_25以及所有字段的列名和数据类型。

分布式爬虫怎么处理Redis里的数据

6.执行下面程序: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()

分布式爬虫怎么处理Redis里的数据

感谢各位的阅读,以上就是“分布式爬虫怎么处理Redis里的数据”的内容了,经过本文的学习后,相信大家对分布式爬虫怎么处理Redis里的数据这一问题有了更深刻的体会,具体使用情况还需要大家实践验证。这里是亿速云,小编将为大家推送更多相关知识点的文章,欢迎关注!

推荐阅读:
  1. 存储到redis里一般是什么数据
  2. springboot集成测试里的redis

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

redis

上一篇:怎么在Java移动文件夹

下一篇:vue-router的工作原理

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》