python爬取音乐排行_python爬取网易云音乐热歌榜实例代码
时间: 2023-10-04 19:13:23 浏览: 387
以下是用 Python 爬取网易云音乐热歌榜的实例代码:
```python
import requests
from bs4 import BeautifulSoup
url = 'https://music.163.com/discover/toplist'
headers = {
'Referer': 'https://music.163.com/',
'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')
song_list = soup.find_all('div', class_='ttc')
for song in song_list:
print(song.a.attrs['title'])
```
解析:
1. 使用 requests 模块请求网页源代码。
2. 使用 BeautifulSoup 模块解析网页源代码,并通过类名查找到歌曲列表。
3. 遍历歌曲列表,获取每首歌曲的名称并输出。
相关问题
python爬取网易云音乐飙升榜音乐_python爬取网易云音乐热歌榜 python爬取网易云音乐热歌榜实例代码...
好的,以下是Python爬取网易云音乐热歌榜的实例代码:
```python
import requests
from bs4 import BeautifulSoup
url = 'https://music.163.com/discover/toplist?id=3778678' # 网易云音乐热歌榜的URL
headers = {
'Referer': 'https://music.163.com/',
'Host': 'music.163.com',
'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')
song_list = soup.find('ul', class_='f-hide').find_all('a') # 获取歌曲列表
for song in song_list:
print(song.text) # 输出歌曲名称
```
运行上述代码,即可爬取网易云音乐热歌榜的歌曲列表。同理,如果要爬取飙升榜的歌曲列表,只需将URL改为`'https://music.163.com/discover/toplist?id=19723756'`即可。
用python编写一个selenium脚本爬取网易云音乐排名前100的歌曲
当然可以!下面是一个基本的Python脚本,使用Selenium库来爬取网易云音乐排名前100的歌曲:
```python
from selenium import webdriver
# 创建一个Chrome览器实例
driver = webdriver.Chrome()
# 打开网易云音乐排行榜页面
driver.get('https://music.163.com/#/discover/toplist?id=3779629')
# 切换到iframe内嵌页面
driver.switch_to.frame('contentFrame')
# 定位到歌曲列表
song_list = driver.find_elements_by_xpath('//tbody/tr')
# 遍历歌曲列表并输出歌曲名和歌手名
for song in song_list:
song_name = song.find_element_by_xpath('./td[2]/div/div/div/span/a/b').get_attribute('title')
artist_name = song.find_element_by_xpath('./td[4]/div/div/div/span').get_attribute('title')
print("歌曲名:", song_name)
print("歌手名:", artist_name)
print("--------------------")
# 关闭浏览器实例
driver.quit()
```
这个脚本首先创建了一个Chrome浏览器实例,然后打开网易云音乐排行榜页面。接下来,切换到内嵌的iframe页面,定位到歌曲列表,并使用XPath表达式获取每首歌曲的名称和歌手名称。最后,遍历歌曲列表并输出结果。
请确保已经安装了Selenium库,并且根据需要选择合适的浏览器驱动。在这个例子中,使用了Chrome浏览器和对应的Chrome驱动。