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等。

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

相关推荐
阿尔的代码屋14 小时前
[大模型实战 07] 基于 LlamaIndex ReAct 框架手搓全自动博客监控 Agent
人工智能·python
AI探索者1 天前
LangGraph StateGraph 实战:状态机聊天机器人构建指南
python
AI探索者1 天前
LangGraph 入门:构建带记忆功能的天气查询 Agent
python
FishCoderh1 天前
Python自动化办公实战:批量重命名文件,告别手动操作
python
躺平大鹅1 天前
Python函数入门详解(定义+调用+参数)
python
曲幽1 天前
我用FastAPI接ollama大模型,差点被asyncio整崩溃(附对话窗口实战)
python·fastapi·web·async·httpx·asyncio·ollama
两万五千个小时2 天前
落地实现 Anthropic Multi-Agent Research System
人工智能·python·架构
哈里谢顿2 天前
Python 高并发服务限流终极方案:从原理到生产落地(2026 实战指南)
python
用户8356290780512 天前
无需 Office:Python 批量转换 PPT 为图片
后端·python
markfeng82 天前
Python+Django+H5+MySQL项目搭建
python·django