本文示範如何使用 Python 標準庫 urllib 與正則表達式,從百度音樂的分類頁面解析歌曲連結並批量下載 MP3 檔案。注意:僅供技術學習參考,請遵守網站服務條款與著作權法規。
/song/數字)。https://music.baidu.com/song/{id}/download)。urllib.urlretrieve 下載並以歌曲標題命名儲存。#!/usr/bin/env python
# -*- coding: utf-8 -*-
import urllib
import re
base_url = "https://music.baidu.com"
tag_url = "https://music.baidu.com/search/tag?key=經典流行"
html = urllib.urlopen(tag_url).read()
# 提取歌曲 ID
song_ids = re.findall(r'/song/(\d+)', html)
download_links = []
for sid in song_ids:
download_links.insert(0, f"{base_url}/song/{sid}/download")
for link in download_links:
try:
page = urllib.urlopen(link).read()
# 提取真實 MP3 連結
mp3_url = re.search(r'https://[^ ]*xcode\.[a-z0-9]*', page).group()
# 提取歌曲標題
title_match = re.search(r'title="([^"]*)', page)
title = title_match.group(1) if title_match else sid
# 下載
urllib.urlretrieve(mp3_url, f"{title}.mp3")
print(f"Downloaded: {title}.mp3")
except Exception as e:
print(f"Failed {link}: {e}")
BeautifulSoup 或 lxml 解析器,更穩健。try/except 避免中斷整批流程。utf-8 聲明,Python 3 原生支援)。import requests
from bs4 import BeautifulSoup
import os
headers = {'User-Agent': 'Mozilla/5.0 ...'}
resp = requests.get(tag_url, headers=headers)
soup = BeautifulSoup(resp.text, 'html.parser')
# 使用 CSS 選擇器或 find_all 更可靠地提取資料
音樂版權受法律保護,批量下載可能構成侵權。本程式碼僅作為網路爬蟲技術練習,請勿用於商業用途或大量散播,應支持正版音樂服務。