python爬酷狗音乐所有歌手
时间: 2023-07-17 10:53:40 浏览: 61
为了爬取酷狗音乐的所有歌手,我们可以使用Python中的爬虫库requests和正则表达式re来实现。以下是一个简单的爬虫代码示例:
```python
import requests
import re
# 获取所有歌手的URL
url = "http://www.kugou.com/yy/singer/index/1-all-0.html"
response = requests.get(url)
html = response.text
# 使用正则表达式匹配每个歌手的URL和名称
pattern = r'<a href="/yy/singer/home/\d+.html" title="(.+?)" target="_blank">'
singers = re.findall(pattern, html)
# 输出所有歌手的名称
for singer in singers:
print(singer)
```
这段代码首先通过requests库获取包含所有歌手的页面HTML代码,然后使用正则表达式匹配每个歌手的URL和名称,并输出所有歌手的名称。你可以根据需要修改代码以满足你的需求。
相关问题
python爬虫酷狗音乐
你可以使用Python来编写爬虫程序来获取酷狗音乐的数据。以下是一个简单的示例代码:
```python
import requests
from bs4 import BeautifulSoup
# 设置请求头信息,模拟浏览器访问
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'
}
# 发送GET请求获取网页内容
url = 'http://www.kugou.com/yy/rank/home/1-8888.html?from=homepage'
response = requests.get(url, headers=headers)
html = response.text
# 使用BeautifulSoup解析html
soup = BeautifulSoup(html, 'html.parser')
# 找到包含歌曲信息的元素
songs = soup.find_all('li', class_='pc_temp_songlist')
# 遍历歌曲信息并获取相关数据
for song in songs:
# 获取歌曲名称
name = song.find('a', class_='pc_temp_songname').text.strip()
# 获取歌手名称
singer = song.find('a', class_='pc_temp_singername').text.strip()
# 打印歌曲信息
print(f"歌曲:{name},歌手:{singer}")
```
这段代码使用了requests库发送GET请求,并使用BeautifulSoup库解析HTML页面。你可以根据自己的需求进一步处理获取到的数据。请注意,爬取网站的数据需要遵守相关的法律法规,确保你的行为合法合规。
python爬虫酷狗音乐top20
以下是爬取酷狗音乐TOP20的Python代码:
```python
import requests
from bs4 import BeautifulSoup
import csv
# 请求头信息
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'}
# 获取HTML页面
def get_html(url):
try:
r = requests.get(url, headers=headers)
r.raise_for_status()
r.encoding = r.apparent_encoding
return r.text
except:
return ""
# 解析HTML页面
def parse_html(html):
soup = BeautifulSoup(html, 'html.parser')
ranks = soup.find_all('span', class_='pc_temp_num')
titles = soup.find_all('a', class_='pc_temp_songname')
times = soup.find_all('span', class_='pc_temp_time')
for rank, title, time in zip(ranks, titles, times):
rank = rank.get_text().strip()
title = title.get_text().split('-')[1].strip()
author = title.get_text().split('-')[0].strip()
time = time.get_text().strip()
yield {'rank': rank, 'title': title, 'author': author, 'time': time}
# 保存数据到CSV文件
def save_to_csv(data):
with open('music.csv', 'w', newline='', encoding='utf-8-sig') as f:
writer = csv.writer(f)
writer.writerow(['排名', '歌曲名称', '歌手', '时长'])
for item in data:
writer.writerow([item['rank'], item['title'], item['author'], item['time']])
# 主函数
def main():
url = 'https://www.kugou.com/yy/rank/home/1-8888.html?from=rank'
html = get_html(url)
data = parse_html(html)
save_to_csv(data)
if __name__ == '__main__':
main()
```