喜馬拉雅音頻頁面通過 JSON API 返回播放地址。本文提供 **Lua + luacurl + luajson** 命令行腳本,輸入音頻 ID 直接輸出 MP3 下載鏈接。
luacurl:https://luacurl.luaforge.net/ (LuaBinding for libcurl)luajson:https://github.com/mbalmer/luajson (JSON 解析)apt/yum install lua-curl lua-json。
#!/usr/bin/lua5.1
require("luacurl")
require("json")
-- 通用 HTTP GET 返回字符串
function get_html(url, c)
local result = {}
if c == nil then c = curl.new() end
c:setopt(curl.OPT_URL, url)
c:setopt(curl.OPT_WRITEDATA, result)
c:setopt(curl.OPT_WRITEFUNCTION, function(tab, buffer)
table.insert(tab, buffer)
return #buffer
end)
local ok = c:perform()
return ok, table.concat(result)
end
-- 解析喜馬拉雅 JSON 獲取 MP3 地址
function down_mp3(id)
local url = "https://www.ximalaya.com/tracks/" .. id .. ".json"
local mp3_prefix = "https://fdfs.xmcdn.com/"
local ok, html = get_html(url)
if ok then
local result = json.decode(html)
print(mp3_prefix .. result.play_path_64) -- 64kbps 高質量地址
else
print("error")
end
end
-- 命令行參數
if arg[1] and tonumber(arg[1]) then
down_mp3(arg[1])
else
print("請輸入音頻 ID")
end
chmod +x ximalaya.lua
./ximalaya.lua 12345678
# 輸出: https://fdfs.xmcdn.com/xxxxxx.mp3
curl.OPT_WRITEFUNCTION 回調累積響應體到 table,最後 table.concat 合併。play_path_64 (64kbps)、play_path_32 (32kbps) 等字段。luacurl 支持多 easy handle 並發,或用 lua-nginx-module cosocket 異步。lua-id3 或外部工具)。Lua 配合 luacurl/luajson 可快速構建輕量爬蟲。**核心邏輯:HTTP GET → JSON 解析 → 字段提取**,幾十行代碼即可實用。生產級爬蟲需加入限流、重試、代理池、去重、監控等工程化組件。