分布式爬蟲處理Redis里的數(shù)據(jù)操作步驟
存入MongoDB
1.啟動(dòng)MongoDB數(shù)據(jù)庫(kù):sudo mongod
2.執(zhí)行下面程序:py2 process_youyuan_mongodb.py
# process_youyuan_mongodb.py # -*- coding: utf-8 -*- import json import redis import pymongo def main(): # 指定Redis數(shù)據(jù)庫(kù)信息 rediscli = redis.StrictRedis(host='192.168.199.108', port=6379, db=0) # 指定MongoDB數(shù)據(jù)庫(kù)信息 mongocli = pymongo.MongoClient(host='localhost', port=27017) # 創(chuàng)建數(shù)據(jù)庫(kù)名 db = mongocli['youyuan'] # 創(chuàng)建表名 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.啟動(dòng)mysql:mysql.server start(更平臺(tái)不一樣)
2.登錄到root用戶:mysql -uroot -p
3.創(chuàng)建數(shù)據(jù)庫(kù)youyuan:create database youyuan;
4.切換到指定數(shù)據(jù)庫(kù):use youyuan
5.創(chuàng)建表beijing_18_25以及所有字段的列名和數(shù)據(jù)類型。
6.執(zhí)行下面程序:py2 process_youyuan_mysql.py
#process_youyuan_mysql.py # -*- coding: utf-8 -*- import json import redis import MySQLdb def main(): # 指定redis數(shù)據(jù)庫(kù)信息 rediscli = redis.StrictRedis(host='192.168.199.108', port = 6379, db = 0) # 指定mysql數(shù)據(jù)庫(kù) 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()方法獲取操作游標(biāo) cur = mysqlcli.cursor() # 使用execute方法執(zhí)行SQL INSERT語(yǔ)句 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事務(wù) mysqlcli.commit() #關(guān)閉本次操作 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()
總結(jié)
以上所述是小編給大家介紹的分布式爬蟲處理Redis里的數(shù)據(jù)操作步驟,希望對(duì)大家有所幫助,如果大家有任何疑問歡迎給我留言,小編會(huì)及時(shí)回復(fù)大家的!
相關(guān)文章
Spring+Redis+RabbitMQ開發(fā)限流和秒殺項(xiàng)目功能
本項(xiàng)目將通過整合Springboot和Redis以及Lua腳本來實(shí)現(xiàn)限流和秒殺的效果,將通過RabbitMQ消息隊(duì)列來實(shí)現(xiàn)異步保存秒殺結(jié)果的效果,對(duì)Spring?Redis?RabbitMQ限流秒殺功能實(shí)現(xiàn)感興趣的朋友一起看看吧2022-02-02使用Spring?Boot實(shí)現(xiàn)Redis鍵過期回調(diào)功能示例詳解
這篇文章主要介紹了使用Spring?Boot實(shí)現(xiàn)Redis鍵過期回調(diào)功能,就是一個(gè)實(shí)現(xiàn)Redis鍵過期回調(diào)功能的Spring?Boot應(yīng)用的示例,代碼簡(jiǎn)單易懂,對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2023-07-07使用Redis獲取數(shù)據(jù)轉(zhuǎn)json,解決動(dòng)態(tài)泛型傳參的問題
這篇文章主要介紹了使用Redis獲取數(shù)據(jù)轉(zhuǎn)json,解決動(dòng)態(tài)泛型傳參的問題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來看看吧2020-07-07