通过拦截网络请求,只需少量JavaScript代码即可快速获取网易云音乐的音频直链。以下是完整实现方案:
实现原理
- XHR请求拦截 - 重写
XMLHttpRequest构造函数 - 请求监听 - 通过
open方法拦截所有API请求 - 响应过滤 - 检测包含
.m4a或.mp3的响应 - 直链提取 - 解析JSON数据获取音频直链
- 自动触发 - 用
window.open()触发浏览器下载
操作步骤
- 控制台执行下面的代码:
(function() {
'use strict';
const OriginalXHR = window.XMLHttpRequest;
window.XMLHttpRequest = function() {
const xhr = new OriginalXHR();
const originalOpen = xhr.open;
xhr.open = function(method, url, async = true, user = null, password = null) {
console.log('XHR 请求信息:');
console.log('方法:', method);
console.log('URL:', url);
console.log('是否异步:', async);
originalOpen.call(this, method, url, async, user, password);
};
xhr.addEventListener('readystatechange', function() {
if (xhr.readyState === 4 || xhr.readyState === 3) {
console.log('XHR 响应信息:');
console.log('状态码:', xhr.status);
console.log('状态文本:', xhr.statusText);
console.log('响应内容:', xhr.responseText);
if (xhr.responseText.includes('.m4a') || xhr.responseText.includes('.mp3') || xhr.responseText.includes('.wav')) {
const json = JSON.parse(xhr.responseText);
window.open(json.data[0].url);
}
}
});
return xhr;
};
})();
2. 点击任意播放按钮:
3. 此时弹出一个可直接下载的音频播放页面:
通过这个方案,我们绕过了官方客户端限制,直接获取音频源文件。虽然需要手动操作,但比传统爬虫更轻量。技术本身是中立的,请务必在合法合规范围内使用。