# Python怎么爬取網易云音樂
## 前言
在當今大數據時代,網絡爬蟲技術成為了獲取互聯網數據的重要手段之一。作為國內最受歡迎的音樂平臺之一,網易云音樂擁有海量的音樂資源和用戶數據,這些數據對于音樂推薦、市場分析等場景具有重要價值。本文將詳細介紹如何使用Python爬取網易云音樂的數據,包括歌曲信息、評論數據等。
## 準備工作
### 1. 環境配置
首先需要確保你的Python環境已經安裝好,推薦使用Python 3.6及以上版本。此外,還需要安裝以下必要的庫:
```bash
pip install requests
pip install beautifulsoup4
pip install selenium
pip install pycryptodome
在開始爬取之前,我們需要先分析網易云音樂網站的結構和反爬機制:
網易云音樂的歌曲信息可以通過公開API獲取,以下是獲取歌曲基本信息的方法:
import requests
def get_song_info(song_id):
url = f'https://music.163.com/api/song/detail/?ids=[{song_id}]'
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36'
}
response = requests.get(url, headers=headers)
if response.status_code == 200:
return response.json()
return None
# 示例:獲取周杰倫《晴天》的信息(歌曲ID: 186721)
song_info = get_song_info(186721)
print(song_info)
類似地,我們可以獲取歌手的基本信息:
def get_artist_info(artist_id):
url = f'https://music.163.com/api/artist/{artist_id}'
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36'
}
response = requests.get(url, headers=headers)
if response.status_code == 200:
return response.json()
return None
# 示例:獲取周杰倫的信息(歌手ID: 6452)
artist_info = get_artist_info(6452)
print(artist_info)
網易云音樂的核心API都采用了加密參數,我們需要破解這些加密才能獲取更多數據。
網易云音樂主要使用了以下加密方式: - 參數加密:使用AES加密 - 簽名生成:使用MD5和自定義算法
我們需要實現網易云音樂的加密算法:
from Crypto.Cipher import AES
from Crypto.Util.Padding import pad
import base64
import hashlib
import random
import json
def aes_encrypt(text, key):
iv = '0102030405060708'
cipher = AES.new(key.encode(), AES.MODE_CBC, iv.encode())
padded_text = pad(text.encode(), AES.block_size)
encrypted = cipher.encrypt(padded_text)
return base64.b64encode(encrypted).decode()
def generate_params(data):
text = json.dumps(data)
key = '0CoJUm6Qyw8W8jud'
params = aes_encrypt(text, key)
params = aes_encrypt(params, 'a' * 16)
return params
def generate_encSecKey():
return '257348aecb5e556c066de214e531faadd1c55d814f9be95fd06d6bff9f4c7a41f831f6394d5a3fd2e3881736d94a02ca919d952872e7d0a50ebfa1769a7a62d512f5f1ca21aec60bc3819a9c3ffca5eca9a0dba6d6f7249b06f5965ecfff3695b54e1c28f3f624750ed39e7de08fc8493242e26dbc4484a01c76f739e135637c'
使用加密參數獲取歌曲評論:
def get_song_comments(song_id, limit=20, offset=0):
url = 'https://music.163.com/weapi/v1/resource/comments/R_SO_4_{}?csrf_token='.format(song_id)
data = {
'rid': 'R_SO_4_' + str(song_id),
'offset': offset,
'total': 'true',
'limit': limit,
'csrf_token': ''
}
params = generate_params(data)
encSecKey = generate_encSecKey()
payload = {
'params': params,
'encSecKey': encSecKey
}
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36',
'Referer': 'https://music.163.com/'
}
response = requests.post(url, data=payload, headers=headers)
if response.status_code == 200:
return response.json()
return None
# 示例:獲取《晴天》的前20條評論
comments = get_song_comments(186721)
print(comments)
要獲取用戶私人數據或突破某些限制,需要模擬登錄:
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
def login_163(email, password):
driver = webdriver.Chrome()
driver.get('https://music.163.com/')
# 點擊登錄按鈕
login_btn = WebDriverWait(driver, 10).until(
EC.element_to_be_clickable((By.LINK_TEXT, "登錄"))
)
login_btn.click()
# 切換到iframe
WebDriverWait(driver, 10).until(
EC.frame_to_be_available_and_switch_to_it((By.ID, "g_iframe"))
)
# 選擇郵箱登錄
email_login = WebDriverWait(driver, 10).until(
EC.element_to_be_clickable((By.LINK_TEXT, "選擇其他登錄模式"))
)
email_login.click()
# 輸入郵箱和密碼
email_input = driver.find_element(By.NAME, 'email')
email_input.send_keys(email)
password_input = driver.find_element(By.NAME, 'password')
password_input.send_keys(password)
# 點擊登錄
submit_btn = driver.find_element(By.ID, 'dologin')
submit_btn.click()
# 等待登錄完成
WebDriverWait(driver, 10).until(
EC.presence_of_element_located((By.CLASS_NAME, "user-avatar"))
)
# 獲取cookies
cookies = driver.get_cookies()
driver.quit()
return cookies
網易云音樂在頻繁請求時會要求驗證碼,可以嘗試以下方法:
獲取到的數據可以存儲到文件或數據庫中:
import csv
def save_comments_to_csv(comments, filename):
with open(filename, 'w', newline='', encoding='utf-8') as f:
writer = csv.writer(f)
writer.writerow(['用戶ID', '昵稱', '評論內容', '點贊數', '時間'])
for comment in comments['comments']:
writer.writerow([
comment['user']['userId'],
comment['user']['nickname'],
comment['content'],
comment['likedCount'],
comment['time']
])
# 示例:保存評論到CSV
comments = get_song_comments(186721, limit=100)
if comments:
save_comments_to_csv(comments, 'comments.csv')
本文詳細介紹了如何使用Python爬取網易云音樂的數據,包括基礎信息獲取、加密API破解、模擬登錄等高級技巧。需要注意的是,網絡爬蟲技術應當合理合法使用,尊重網站的數據權益和用戶隱私。
在實際應用中,你可能還需要處理更多復雜情況,如IP封禁、驗證碼識別等。建議在開發過程中逐步完善你的爬蟲程序,并始終遵循合法合規的原則。
希望本文對你學習網絡爬蟲技術有所幫助!如果你有任何問題或建議,歡迎留言討論。 “`
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。