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

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

相关推荐
曲幽3 小时前
FastAPI + PostgreSQL 实战:从入门到不踩坑,一次讲透
python·sql·postgresql·fastapi·web·postgres·db·asyncpg
用户8356290780518 小时前
使用 C# 在 Excel 中创建数据透视表
后端·python
码路飞11 小时前
FastMCP 实战:一个 .py 文件,给 Claude Code 装上 3 个超实用工具
python·ai编程·mcp
dev派13 小时前
AI Agent 系统中的常用 Workflow 模式(2) Evaluator-Optimizer模式
python·langchain
前端付豪15 小时前
AI 数学辅导老师项目构想和初始化
前端·后端·python
用户03321266636715 小时前
将 PDF 文档转换为图片【Python 教程】
python
悟空爬虫16 小时前
UV实战教程,我啥要从Anaconda切换到uv来管理包?
python
dev派16 小时前
AI Agent 系统中的常用 Workflow 模式(1)
python·langchain
明月_清风18 小时前
从“能用”到“专业”:构建生产级装饰器与三层逻辑拆解
后端·python
曲幽1 天前
数据库实战:FastAPI + SQLAlchemy 2.0 + Alembic 从零搭建,踩坑实录
python·fastapi·web·sqlalchemy·db·asyncio·alembic