Python爬蟲之使用MongoDB存儲數據

1.MongoDB的安裝

MongoDB是一種非關係型數據庫html

MongoDB官網git

選擇你的系統對應的版本下載安裝便可github

2.MongoDB配置

a.在C盤或者D盤建一個文件夾如圖mongodbmongodb

b.安裝成功后里面會有bin文件而後再文件夾裏面新建一個data文件夾,data文件裏面新建db文件夾 數據庫

db文件夾用於存儲MongoDB數據

c.在bin文件路徑下打開命令行工具執行下面的命令bash

mongod --dbpath C:\mongdb\data\db
複製代碼

注意:文件夾路徑以本身所建的爲準

d.此時在打開一個命令行在bin路徑下執行下面的代碼app

mongo
複製代碼

3.安裝第三方庫pymongo(鏈接MongoDB)

pip3 install pymongo
複製代碼

4.安裝Mongodb可視化管理工具Robomongo

Robomongo官網工具

安裝成功以後啓動Robomongo,在空白處點擊,而後選擇Add命令,單擊Save,最後點擊Connect按鈕鏈接到MongoDB數據庫post

5.案例代碼

引入相應的模塊學習

import requests
from lxml import etree
import re
import pymongo
import time
複製代碼

鏈接mongodb數據庫

client = pymongo.MongoClient('localhost', 27017)
mydb = client['mydb']
musictop = mydb['musictop']
複製代碼

案例完整代碼

import requests
from lxml import etree
import re
import pymongo
import time

client = pymongo.MongoClient('localhost', 27017)
mydb = client['mydb']
musictop = mydb['musictop']

headers = {
    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/66.0.3359.181 Safari/537.36'
}

def get_url_music(url):
    html = requests.get(url, headers=headers)
    selector = etree.HTML(html.text)
    music_hrefs = selector.xpath('//a[@class="nbg"]/@href')
    for music_href in music_hrefs:
        get_music_info(music_href)

def get_music_info(url):
    html = requests.get(url, headers=headers)
    selector = etree.HTML(html.text)
    name = selector.xpath('//*[@id="wrapper"]/h1/span/text()')[0]
    author = re.findall('表演者:.*?>(.*?)</a>', html.text,re.S)[0]
    styles = re.findall('<span class="pl">流派:</span>&nbsp;(.*?)<br/>',html.text,re.S)
    if len(styles) == 0:
        style = '未知'
    else:
        style = styles[0].strip()
    time = re.findall('發行時間:</span>&nbsp;(.*?)<br/>', html.text, re.S)[0].strip()
    publishers = re.findall('出版者:.*?>(.*?)</a>', html.text, re.S)

    if len(publishers) == 0:
        publishers = '未知'
    else:
        publishers = publishers[0].strip()
    score = selector.xpath('//*[@id="interest_sectl"]/div/div[2]/strong/text()')[0]
    print(name, author, style, time, publishers, score)
    info = {
        'name': name,
        'author': author,
        'style': style,
        'time': time,
        'publisher': publishers,
        'score': score
    }

    musictop.insert_one(info)

if __name__ == '__main__':
    urls = ['https://music.douban.com/top250?start={}'.format(str(i)) for i in range(0, 250, 25)]
    for url in urls:
        get_url_music(url)
        time.sleep(2)
複製代碼

6.執行爬蟲代碼,而後到Robomongo刷新就會看到數據已經有啦

7.本文配套的demo

GitHub地址

8.本文只是入門級別,我分享出來但願和你們一塊兒學習進步! 我還寫了Vue插件開發和搶紅包的小遊戲(歡迎Star)

Vue插件開發

搶紅包小遊戲

Python爬蟲入門

相關文章
相關標籤/搜索