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

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

相关推荐
孟健8 小时前
Karpathy 用 200 行纯 Python 从零实现 GPT:代码逐行解析
python
码路飞10 小时前
写了个 AI 聊天页面,被 5 种流式格式折腾了一整天 😭
javascript·python
曲幽12 小时前
FastAPI压力测试实战:Locust模拟真实用户并发及优化建议
python·fastapi·web·locust·asyncio·test·uvicorn·workers
敏编程16 小时前
一天一个Python库:jsonschema - JSON 数据验证利器
python
前端付豪17 小时前
LangChain记忆:通过Memory记住上次的对话细节
人工智能·python·langchain
databook17 小时前
ManimCE v0.20.1 发布:LaTeX 渲染修复与动画稳定性提升
python·动效
花酒锄作田1 天前
使用 pkgutil 实现动态插件系统
python
前端付豪1 天前
LangChain链 写一篇完美推文?用SequencialChain链接不同的组件
人工智能·python·langchain
曲幽1 天前
FastAPI实战:打造本地文生图接口,ollama+diffusers让AI绘画更听话
python·fastapi·web·cors·diffusers·lcm·ollama·dreamshaper8·txt2img
老赵全栈实战1 天前
Pydantic配置管理最佳实践(一)
python