目录
6.1MongoDB数据库
6.1.1MongoDB的使用
import pymongo
client = pymongo.MongoClient('localhost',27017) #连接MongoDB
mydb = client['mydb'] #连接数据库
test = mydb['test'] #连接表
test.insert_one({'name':'Jan','sex':'男','grade':'88'}) #向表中插入数据
更多操请移步菜鸟教程Windows 平台安装 MongoDB | 菜鸟教程
6.2案例-爬取豆瓣音乐TOP250的数据
(1)爬虫思路分析
(2)观察并且构造URL
https://music.douban.com/top250?start=0
可以看出每一页相隔25,以此来构造出前10页的网址
(3)因为详细页的信息更丰富,本次爬虫在详细页中进行,因此先需要爬取进入详细页的网址连接,进而爬取数据。
(4)爬取的信息有;歌曲名、表演者、流派、发行时间、出版者和评分等
(5)爬虫代码分析
import requests
import time
import re
import pymongo
from lxml import etree #导入相应的库文件
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/90.0.4430.93 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 = selector.xpath('//*[@id="info"]/span[1]/span/a/text()')
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