MongoDB是一種非關係型數據庫html
MongoDB官網git
選擇你的系統對應的版本下載安裝便可github
a.在C盤或者D盤建一個文件夾如圖mongodbmongodb
b.安裝成功后里面會有bin文件而後再文件夾裏面新建一個data文件夾,data文件裏面新建db文件夾 數據庫
db文件夾用於存儲MongoDB數據c.在bin文件路徑下打開命令行工具執行下面的命令bash
mongod --dbpath C:\mongdb\data\db
複製代碼
注意:文件夾路徑以本身所建的爲準
d.此時在打開一個命令行在bin路徑下執行下面的代碼app
mongo
複製代碼
pip3 install pymongo
複製代碼
安裝成功以後啓動Robomongo,在空白處點擊,而後選擇Add命令,單擊Save,最後點擊Connect按鈕鏈接到MongoDB數據庫post
引入相應的模塊學習
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> (.*?)<br/>',html.text,re.S)
if len(styles) == 0:
style = '未知'
else:
style = styles[0].strip()
time = re.findall('發行時間:</span> (.*?)<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)
複製代碼