python3 实现爬取TOP500的音乐信息并存储到mongoDB数据库中
作者:shawn xie123 时间:2024-01-21 06:11:12
爬取TOP500的音乐信息,包括排名情况、歌曲名、歌曲时间。
网页版酷狗不能手动翻页进行下一步的浏览,仔细观察第一页的URL:
http://www.kugou.com/yy/rank/home/1-8888.html
这里尝试将1改为2,再进行浏览,恰好是第二页的信息,再改为3,恰好是第三页的信息,多次尝试发现不同的数字即为不同的页面。因此只需更改home/后面的数字即可。由于每页显示的为22首歌曲,所以总共需要23个URL。
import requests
from bs4 import BeautifulSoup
from time import sleep
import pymongo
#连接数据库
client = pymongo.MongoClient(‘localhost',27017)
mydb = client[‘yourdb']
#创建数据库
musicTop = mydb[‘musicTop']
#使用header是用于伪装为浏览器,让爬虫更稳定
Headers = {
‘User-Agent': ‘Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.67 Safari/537.36'
}
#定义获取信息的函数
def get_info(url):
wd_data = requests.get(url,headers=Headers)
soup = BeautifulSoup(wd_data.text,‘lxml')
#获取排名情况
ranks = soup.select(‘span.pc_temp_num')
#获取标题
titles = soup.select(‘div.pc_temp_songlist > ul > li > a')
#获取时间
times = soup.select(‘span.pc_temp_tips_r > span')
for rank,title,time in zip(ranks,titles,times):
data = {
‘rank':rank.get_text().strip(),
‘singer':title.get_text(),
‘song':title.get_text(),
‘time':time.get_text().strip()
}
musicTop.insert_one(data) #存入数据库中
if name == ‘main':
urls = [‘http://www.kugou.com/yy/rank/home/{}-8888.html'.format(number) for number in range(1,24)]
for url in urls:
get_info(url)
sleep(2)
运行后,爬取的数据在mongoDB数据库中显示如下:
来源:https://blog.csdn.net/xiezhiming1234/article/details/84673459
标签:python3,爬取,音乐,mongoDB
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
对pandas通过索引提取dataframe的行方法详解
2021-05-18 18:10:39
![](https://img.aspxhome.com/file/2023/7/90407_0s.jpg)
asp自带的内存缓存 application
2011-03-09 11:18:00
python requests.post带head和body的实例
2022-07-12 01:22:59
操作Windows注册表的简单的Python程序制作教程
2023-01-04 00:17:40
基于Python实现自动扫雷详解
2023-09-07 23:31:20
![](https://img.aspxhome.com/file/2023/9/86389_0s.gif)
怎么让按钮更容易被点击
2007-08-22 09:07:00
![](https://img.aspxhome.com/file/UploadPic/20078/22/200782291027419s.gif)
python实现网页录音效果
2022-03-19 08:07:15
![](https://img.aspxhome.com/file/2023/3/118063_0s.jpg)
如何利用python写GUI及生成.exe可执行文件
2023-06-26 00:42:57
![](https://img.aspxhome.com/file/2023/4/59824_0s.png)
Django Paginator分页器的使用示例
2021-10-25 02:36:39
![](https://img.aspxhome.com/file/2023/4/127904_0s.png)
SqlServer2016模糊匹配的三种方式及效率问题简析
2024-01-22 09:45:59
python字符串,数值计算
2022-12-28 11:20:32
Oracle 函数大全
2009-07-23 14:29:00
收集前端面试题之url、href、src
2024-06-05 09:12:30
js控制多图左右滚动切换效果代码分享
2023-08-28 00:14:32
![](https://img.aspxhome.com/file/2023/0/56190_0s.jpg)
Pandas Matplotlib保存图形时坐标轴标签太长导致显示不全问题的解决
2023-07-22 20:03:09
![](https://img.aspxhome.com/file/2023/0/62940_0s.png)
Python爬取智联招聘数据分析师岗位相关信息的方法
2021-04-23 15:01:02
![](https://img.aspxhome.com/file/2023/2/133502_0s.png)
Random 在 Python 中的使用方法
2022-04-29 14:21:37
![](https://img.aspxhome.com/file/2023/3/131093_0s.png)
python实现简单登陆系统
2023-05-25 06:50:49
sql使用cast进行数据类型转换示例
2024-01-14 07:42:11
String.indexOf 方法介绍
2013-06-01 20:22:27