0
点赞
收藏
分享

微信扫一扫

Go语言中的`os.WriteFile`:简单高效的文件写入方法

yundejia 2024-11-12 阅读 8

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

环境准备

  • Python 3.x
  • requests 库
  • BeautifulSoup 库

安装依赖

pip install requests beautifulsoup4

代码

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,然后在命令行中运行:

python get_hot_songs.py

注意事项

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

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

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

举报

相关推荐

0 条评论