依關鍵字搜尋百度音樂(如「經典流行」),解析搜尋結果頁面取得歌曲 ID,組裝下載連結,批量下載 MP3 檔案。
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import urllib.request
import re
import os
BASE_URL = "https://music.baidu.com"
SEARCH_URL = "https://music.baidu.com/search/tag?key=經典流行"
HEADERS = {"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36"}
def fetch_html(url):
req = urllib.request.Request(url, headers=HEADERS)
return urllib.request.urlopen(req).read().decode("utf-8", errors="ignore")
def extract_song_ids(html):
# 搜尋結果頁面中的歌曲連結格式:/song/123456
return re.findall(r'/song/(\d+)', html)
def get_download_url(song_id):
# 歌曲頁面包含下載連結
page = fetch_html(f"{BASE_URL}/song/{song_id}/download")
# 頁面中找真實 MP3 連結(簡化版正則)
m = re.search(r'https://[^"\']+\.mp3', page)
return m.group(0) if m else None
def get_song_title(song_id):
page = fetch_html(f"{BASE_URL}/song/{song_id}")
m = re.search(r'([^<]+) ', page)
return m.group(1).replace(" - 百度音樂", "").strip() if m else song_id
def download_mp3(url, filename, dest_dir="downloads"):
os.makedirs(dest_dir, exist_ok=True)
path = os.path.join(dest_dir, filename)
if os.path.exists(path):
print(f"跳過已存在:{filename}")
return
urllib.request.urlretrieve(url, path)
print(f"已下載:{filename}")
def main():
html = fetch_html(SEARCH_URL)
song_ids = extract_song_ids(html)
print(f"共找到 {len(song_ids)} 首歌曲")
for sid in song_ids[:10]: # 示範只下載前 10 首
dl_url = get_download_url(sid)
if not dl_url:
print(f"歌曲 {sid} 無下載連結")
continue
title = get_song_title(sid)
safe_title = re.sub(r'[\\/:*?"<>|]', "_", title) # 檔名非法字元替換
download_mp3(dl_url, f"{safe_title}.mp3")
if __name__ == "__main__":
main()
/song/(\d+)、https://[^"']+\.mp3、<title>([^<]+)</title>。\ / : * ? " < > | 等非法字元。os.path.exists 跳過已下載。requests + BeautifulSoup/lxml,解析更穩健。aiohttp + asyncio 非同步下載,大幅提升速度。asyncio.Semaphore)、重試機制(tenacity)。百度音樂內容受版權保護,本程式碼僅示範爬蟲技術原理,請遵守《著作權法》與網站服務條款,支援正版音樂。