首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 更多程式語言 >> 更多程式設計知識

Lua 爬取喜馬拉雅音頻 MP3 地址:luacurl + luajson 實戰

     編輯:更多程式設計知識

喜馬拉雅音頻頁面通過 JSON API 返回播放地址。本文提供 **Lua + luacurl + luajson** 命令行腳本,輸入音頻 ID 直接輸出 MP3 下載鏈接。

依賴安裝

  • luacurl:https://luacurl.luaforge.net/ (LuaBinding for libcurl)
  • luajson:https://github.com/mbalmer/luajson (JSON 解析)
  • Linux 發行版可直接 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 合併。
  • 喜馬拉雅 API 返回 play_path_64 (64kbps)、play_path_32 (32kbps) 等字段。
  • 腳本輕量、無頭瀏覽器、無登錄模擬,**僅供個人學習研究,請遵守網站 robots.txt 與服務條款**。

擴展方向

  • 批量下載專輯:解析專輯頁獲取所有 track ID 循環調用。
  • 並發下載:luacurl 支持多 easy handle 並發,或用 lua-nginx-module cosocket 異步。
  • 元數據保存:ID3 標籤寫入 (需 lua-id3 或外部工具)。

總結

Lua 配合 luacurl/luajson 可快速構建輕量爬蟲。**核心邏輯:HTTP GET → JSON 解析 → 字段提取**,幾十行代碼即可實用。生產級爬蟲需加入限流、重試、代理池、去重、監控等工程化組件。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved