成人在线亚洲_国产日韩视频一区二区三区_久久久国产精品_99国内精品久久久久久久

您的位置:首頁(yè)技術(shù)文章
文章詳情頁(yè)

python爬蟲數(shù)據(jù)保存到mongoDB的實(shí)例方法

瀏覽:115日期:2022-07-16 09:35:05

爬蟲數(shù)據(jù)保存到mongoDB的方法:

import pymongo# 首先需要注意,mongodb數(shù)據(jù)庫(kù)存儲(chǔ)的類型是以鍵值對(duì)類型進(jìn)行存儲(chǔ),所以在存儲(chǔ)以前一定要進(jìn)行數(shù)據(jù)篩選def save_mongo(傳入的數(shù)據(jù)):# 創(chuàng)建連接 因?yàn)槭褂玫臑楸緳C(jī)數(shù)據(jù)庫(kù),所以IP寫localhost即可,端口號(hào)為27017client = pymongo.MongoClient(’localhost’,27017)# 連接數(shù)據(jù)庫(kù)(這里注意一點(diǎn),mongo數(shù)據(jù)庫(kù)有一個(gè)優(yōu)點(diǎn),就是當(dāng)自己連接的數(shù)據(jù)庫(kù)和表都沒有的時(shí)候,會(huì)自動(dòng)創(chuàng)建,所以不用擔(dān)心寫錯(cuò)或者沒有表)db = client[’自己創(chuàng)建數(shù)據(jù)庫(kù)名’]# 連接表collection = db[’自己的表名(mongo中叫做集合)’]# 插入到數(shù)據(jù)庫(kù)中(這里使用dict進(jìn)行強(qiáng)制轉(zhuǎn)換,是為了保證數(shù)據(jù)為字典格式)collection.insert(dict(傳入的數(shù)據(jù)))

mongoDB介紹:

它的特點(diǎn)是高性能、易部署、易使用,存儲(chǔ)數(shù)據(jù)非常方便。主要功能特性有:

*面向集合存儲(chǔ),易存儲(chǔ)對(duì)象類型的數(shù)據(jù)。

*模式自由。

*支持動(dòng)態(tài)查詢。

*支持完全索引,包含內(nèi)部對(duì)象。

*支持查詢。

*支持復(fù)制和故障恢復(fù)。

*使用高效的二進(jìn)制數(shù)據(jù)存儲(chǔ),包括大型對(duì)象(如視頻等)。

*自動(dòng)處理碎片,以支持云計(jì)算層次的擴(kuò)展性。

*支持 Golang,RUBY,PYTHON,JAVA,C++,PHP,C#等多種語言。

*文件存儲(chǔ)格式為BSON(一種JSON的擴(kuò)展)。

*可通過網(wǎng)絡(luò)訪問。

實(shí)例擴(kuò)展:

# coding=utf-8import reimport requestsfrom lxml import etreeimport pymongoimport sysreload(sys)sys.setdefaultencoding(’utf-8’)def getpages(url, total): nowpage = int(re.search(’(d+)’, url, re.S).group(1)) urls = [] for i in range(nowpage, total + 1): link = re.sub(’(d+)’, ’%s’ % i, url, re.S) urls.append(link) return urlsdef spider(url): html = requests.get(url) selector = etree.HTML(html.text) book_name = selector.xpath(’//*[@id='container']/ul/li//div/div[2]/a/text()’) book_author = selector.xpath(’//*[@id='container']/ul/li//div/div[2]/div/a/text()’) saveinfo(book_name, book_author)def saveinfo(book_name, book_author): connection = pymongo.MongoClient() BookDB = connection.BookDB BookTable = BookDB.books length = len(book_name) for i in range(0, length): books = {} books[’name’] = str(book_name[i]).replace(’n’,’’) books[’author’] = str(book_author[i]).replace(’n’,’’) BookTable.insert_one(books)if __name__ == ’__main__’: url = ’http://readfree.me/shuffle/?page=1’ urls = getpages(url,3) for each in urls: spider(each)

以上就是python爬蟲數(shù)據(jù)保存到mongoDB的實(shí)例方法的詳細(xì)內(nèi)容,更多關(guān)于爬蟲數(shù)據(jù)如何保存到mongoDB的資料請(qǐng)關(guān)注好吧啦網(wǎng)其它相關(guān)文章!

標(biāo)簽: Python 編程
相關(guān)文章: