python爬取酷狗音乐排行榜
时间: 2023-10-04 20:03:09 浏览: 160
可以使用 requests 和 BeautifulSoup 库来爬取酷狗音乐排行榜。
首先,需要先确定要爬取的排行榜地址,比如:http://www.kugou.com/yy/rank/home/1-8888.html?from=rank。然后用 requests 库发送 GET 请求获取页面内容。
```python
import requests
url = 'http://www.kugou.com/yy/rank/home/1-8888.html?from=rank'
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)
html = response.text
```
接下来,用 BeautifulSoup 库解析 HTML 内容,并提取排行榜中歌曲的信息。
```python
from bs4 import BeautifulSoup
soup = BeautifulSoup(html, 'lxml')
rank_list = soup.find('ul', class_='rank-list')
song_list = rank_list.find_all('li')
for song in song_list:
# 获取歌曲名
song_name = song.find('a', class_='pc_temp_songname').text.strip()
# 获取歌手名
song_singer = song.find('a', class_='pc_temp_singername').text.strip()
# 获取歌曲排名
song_rank = song.find('span', class_='pc_temp_num').text.strip()
print('{}\t{}\t{}'.format(song_rank, song_name, song_singer))
```
完整代码如下:
```python
import requests
from bs4 import BeautifulSoup
url = 'http://www.kugou.com/yy/rank/home/1-8888.html?from=rank'
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)
html = response.text
soup = BeautifulSoup(html, 'lxml')
rank_list = soup.find('ul', class_='rank-list')
song_list = rank_list.find_all('li')
for song in song_list:
# 获取歌曲名
song_name = song.find('a', class_='pc_temp_songname').text.strip()
# 获取歌手名
song_singer = song.find('a', class_='pc_temp_singername').text.strip()
# 获取歌曲排名
song_rank = song.find('span', class_='pc_temp_num').text.strip()
print('{}\t{}\t{}'.format(song_rank, song_name, song_singer))
```
阅读全文
相关推荐

















