用python写一个爬取音乐
时间: 2023-02-09 13:53:13 浏览: 74
可以使用 Python 的第三方库 BeautifulSoup 来爬取音乐。
首先,需要安装 BeautifulSoup,可以使用 pip 进行安装:
```
pip install beautifulsoup4
```
然后,可以使用 requests 库来获取网页内容,再使用 BeautifulSoup 解析网页。
示例代码:
```
import requests
from bs4 import BeautifulSoup
url = "https://www.example.com/music"
response = requests.get(url)
soup = BeautifulSoup(response.text, 'html.parser')
# 获取音乐名称
music_name = soup.find('div', class_='music_name')
print(music_name.text)
# 获取音乐链接
music_link = soup.find('a', class_='music_link')
print(music_link['href'])
```
请注意,这只是一个简单的示例代码,实际情况可能需要根据具体网站进行修改。
相关问题
用python写一个爬取音乐的代码
以下是一个基于 Python 的爬取音乐的示例代码:
```python
import requests
from bs4 import BeautifulSoup
# 歌曲链接
song_url = 'http://music.163.com/song?id=607341'
# 请求头
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(song_url, headers=headers)
# BeautifulSoup解析页面
soup = BeautifulSoup(response.text, 'html.parser')
# 获取歌曲名和歌手信息
song_name = soup.find('em', {'class': 'f-ff2'}).string
singer_name = soup.find('div', {'class': 'cnt'}).find_all('a')[1].string
# 下载歌曲
download_url = 'http://music.163.com/song/media/outer/url?id={}.mp3'.format(song_url.split('=')[-1])
res = requests.get(download_url, headers=headers)
# 保存到本地
with open('{}.mp3'.format(song_name), 'wb') as f:
f.write(res.content)
print('歌曲:{},歌手:{} 下载完成.'.format(song_name, singer_name))
```
这个代码可以从网易云音乐中爬取指定歌曲的信息以及音频,并将音频保存到本地。请注意在使用时需要替换`song_url`为你需要爬取的歌曲链接。同时,也需要注意爬取行为可能违反相关网站的规定,请自行斟酌使用。
用python写一个爬取酷狗音乐的脚本
以下是一个简单的Python爬取酷狗音乐的脚本:
```python
import requests
from bs4 import BeautifulSoup
# 搜索关键字
keyword = "周杰伦"
# 构造搜索页面URL
search_url = "http://www.kugou.com/yy/html/search.html#searchType=song&searchKeyWord=" + keyword
# 发送GET请求
response = requests.get(search_url)
# 解析HTML
soup = BeautifulSoup(response.text, "html.parser")
# 获取歌曲列表
song_list = soup.select(".song-list > ul > li")
# 遍历歌曲列表
for song in song_list:
# 获取歌曲名称
song_name = song.select(".song-name > a")[0].text
# 获取歌曲链接
song_link = song.select(".song-name > a")[0]["href"]
# 获取歌手名称
artist_name = song.select(".singer-name > a")[0].text
# 输出歌曲信息
print("[歌曲名称]:{}".format(song_name))
print("[歌曲链接]:{}".format(song_link))
print("[歌手名称]:{}".format(artist_name))
```
以上脚本中,首先需要指定搜索关键字,然后构造搜索页面URL。接着,发送GET请求获取搜索结果页面HTML,使用BeautifulSoup解析HTML,获取歌曲列表并遍历。在遍历过程中,获取歌曲名称、链接和歌手名称,并输出到控制台。