使用Axios与JS解析Lazada短链接失败:无法获取完整链接提取商品ID
解决Axios无法解析Lazada短链接重定向的问题
你的代码没拿到重定向后的URL,核心原因是Lazada的短链接大概率不是通过HTTP 3xx状态码做的服务器端重定向,而是用HTML的<meta>刷新标签或者JavaScript前端跳转实现的。Axios的maxRedirects配置只处理HTTP层面的重定向,对前端跳转完全无效。
解决方案
直接请求短链接获取响应内容,手动解析里面的跳转目标URL,步骤如下:
- 模拟浏览器请求头,避免被识别为爬虫
- 分别处理三种常见跳转场景:HTTP重定向、meta刷新、JS跳转
- 提取到完整URL后再解析商品ID
修改后的代码示例
const axios = require('axios'); async function resolveLazadaShortUrl(url) { try { // 禁用自动重定向,先获取原始响应,同时模拟浏览器UA const response = await axios.get(url, { maxRedirects: 0, headers: { 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/118.0.0.0 Safari/537.36' } }); let finalUrl = url; const html = response.data; // 匹配meta刷新跳转 const metaRefreshMatch = html.match(/<meta[^>]+http-equiv="refresh"[^>]+content="\d+;url=(.+?)"/i); if (metaRefreshMatch) { finalUrl = decodeURIComponent(metaRefreshMatch[1]); } // 匹配JS跳转(比如window.location.href) else { const jsRedirectMatch = html.match(/window\.location\.href\s*=\s*["'](.+?)["']/i); if (jsRedirectMatch) { finalUrl = decodeURIComponent(jsRedirectMatch[1]); } } // 处理相对路径转绝对路径 if (!finalUrl.startsWith('http')) { const baseUrl = new URL(url); finalUrl = new URL(finalUrl, baseUrl.origin).href; } // 提取商品ID const productIdMatch = finalUrl.match(/-i(\d+)-/); if (productIdMatch) { console.log('解析到商品ID:', productIdMatch[1]); return productIdMatch[1]; } } catch (error) { // 捕获HTTP重定向错误(因为禁用了自动重定向,3xx会抛出错误) if (error.response?.status >= 300 && error.response?.status < 400) { const finalUrl = error.response.headers.location; const productIdMatch = finalUrl.match(/-i(\d+)-/); if (productIdMatch) { console.log('解析到商品ID:', productIdMatch[1]); return productIdMatch[1]; } } console.error('解析短链接失败:', error.response?.data || error.message); throw error; } } // 调用示例 resolveLazadaShortUrl('https://s.lazada.com.my/s.ny94J');
关键说明
- 模拟浏览器UA是必要的,Lazada会对非浏览器请求做限制
- 覆盖了三种常见的跳转场景,确保能拿到最终的商品链接
- 处理了相对路径的情况,避免解析出无效URL
内容的提问来源于stack exchange,提问作者Ittzsheldon
相关产品推荐
相关产品推荐

