Python爬虫6-数据库存储

目录

6.1MongoDB数据库

6.1.1MongoDB的使用

6.2案例-爬取豆瓣音乐TOP250的数据

6.3Mysql数据库

6.3.1mysql数据库的使用

6.3.2mysql在python的写法

6.4案例-爬取豆瓣电影TOP250数据

6.5Redis数据库

6.5.1Redis的安装

6.5.2Redis的使用

        (1)连接Redis

        (2)Python操作Redis数据库

4.5.3爬取并写入Redis做缓存


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

豆瓣音乐 Top 250

豆瓣音乐 Top 250

可以看出每一页相隔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>&nbsp;(.*?)<br />',html.text,re.S)
    if len(styles) == 0:
        style = '未知'
    else:
        style = styles[0].strip()
    time 
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值