Python爬虫实战 | 爬取网易云音乐热歌榜单

网易云音乐热歌榜单爬虫实战

环境准备

  • Python 3.x
  • requests 库
  • BeautifulSoup 库

安装依赖

bash 复制代码
pip install requests beautifulsoup4

代码

python 复制代码
import requests
from bs4 import BeautifulSoup

def get_cloud_music_hot_songs():
    url = "http://music.163.com/#/discover/playlist"  # 网易云音乐热歌榜单页面
    headers = {
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.3'}

    response = requests.get(url, headers=headers)
    soup = BeautifulSoup(response.text, 'html.parser')
    songs = soup.find_all('li', class_='f-hide')

    hot_songs = []
    for song in songs:
        title = song.find('a').get('title')
        hot_songs.append(title)

    return hot_songs

if __name__ == '__main__':
    hot_songs = get_cloud_music_hot_songs()
    for index, song in enumerate(hot_songs):
        print(f'{index + 1}. {song}')

运行代码

将上述代码保存为 get_hot_songs.py,然后在命令行中运行:

bash 复制代码
python get_hot_songs.py

注意事项

  • 网易云音乐的页面结构可能会发生变化,这会导致爬虫失效。
  • 爬虫应遵循网易云音乐的爬虫协议,不要频繁请求,以免给服务器造成负担。
  • 实际使用时请确保代码的合法性,尊重版权和个人隐私。

以上代码会打印出网易云音乐热歌榜单的前几首歌曲名称。由于网易云音乐的反爬虫机制,这个简单的案例可能无法长期有效。对于复杂的爬虫任务,可能需要使用更高级的技术,如Selenium等。

我们继续学习更高级的技术吧~~

相关推荐
aqi006 小时前
15天学会AI应用开发(八)使用向量数据库实现RAG功能
人工智能·python·大模型·ai编程·ai应用
Csvn7 小时前
`functools.lru_cache` —— 一行代码搞定缓存加速
后端·python
金銀銅鐵1 天前
[Python] 从《千字文》中随机挑选汉字
后端·python
cup111 天前
[技术复盘] Windows Python 打包实战:Nuitka 环境踩坑总结与 CI 自动化构建全指南
python·ai·环境变量·ci·nuitka·skill
aqi001 天前
15天学会AI应用开发(七)有了大模型为什么还要引入RAG
人工智能·python·大模型·ai编程·ai应用
金銀銅鐵1 天前
用 Python 实现 Take-Away 游戏
python·游戏
copyer_xyf1 天前
Agent 流程编排
后端·python·agent
copyer_xyf1 天前
Agent RAG
后端·python·agent