萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> 程式語言綜合

Python 爬取百度音樂分類下載 MP3:urllib + 正則表達式實作

目標

依關鍵字搜尋百度音樂(如「經典流行」),解析搜尋結果頁面取得歌曲 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()

關鍵技術點

  • User-Agent 偽裝:防止 403 Forbidden。
  • 兩層解析:搜尋列表頁 → 歌曲 ID → 歌曲頁面 → 真實 MP3 連結。
  • 正則提取:/song/(\d+)、https://[^"']+\.mp3、<title>([^<]+)</title>。
  • 檔名清洗:移除 \ / : * ? " < > | 等非法字元。
  • 去重與斷點續傳:os.path.exists 跳過已下載。

現代化改良建議

  1. 改用 requests + BeautifulSoup/lxml,解析更穩健。
  2. 使用 aiohttp + asyncio 非同步下載,大幅提升速度。
  3. 加入速率限制(asyncio.Semaphore)、重試機制(tenacity)。
  4. 音樂版權敏感,僅供學習研究,勿商業用途。

法律聲明

百度音樂內容受版權保護,本程式碼僅示範爬蟲技術原理,請遵守《著作權法》與網站服務條款,支援正版音樂。

copyright © 萬盛學電腦網 all rights reserved