分布式爬虫处理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()
存入 MySQL
1.启动mysql:mysql.server start(更平台不一样)
2.登录到root用户:mysql -uroot -p
3.创建数据库youyuan:create database youyuan;
4.切换到指定数据库:use youyuan
5.创建表beijing_18_25以及所有字段的列名和数据类型。
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里的数据操作步骤,希望对大家有所帮助,如果大家有任何疑问欢迎给我留言,小编会及时回复大家的!
相关推荐
聚合室 2020-11-16
天空一样的蔚蓝 2020-10-23
anglehearts 2020-09-09
王道革 2020-11-25
wangdonghello 2020-11-03
Langeldep 2020-11-16
chenhualong0 2020-11-16
koushr 2020-11-12
MRFENGG 2020-11-11
guoyanga 2020-11-10
fackyou00 2020-11-10
Orangesss 2020-11-03
dongCSDN 2020-10-31
rainandtear 2020-10-30
Quietboy 2020-10-30
liuyulong 2020-10-29
fansili 2020-10-29
温攀峰 2020-10-23