如何通过编程获取重定向URL?(使用axios、cheerio遇问题)
解决重定向URL获取问题
一、使用Axios获取重定向URL
如果Axios请求无响应,先排查是否因反爬、请求头缺失导致,以下是两种获取重定向URL的方式:
- 自动跟踪重定向并获取最终URL
Axios默认自动跟踪重定向,可通过响应对象的response.request.res.responseUrl拿到最终跳转后的地址。若初始请求失败,建议添加浏览器UA头模拟真实请求:
const axios = require('axios'); async function getFinalRedirectUrl(url) { try { const response = await axios.get(url, { 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' } }); console.log('最终重定向URL:', response.request.res.responseUrl); return response.request.res.responseUrl; } catch (error) { console.error('请求失败:', error.message); } } getFinalRedirectUrl('你的初始通用URL');
- 获取完整重定向轨迹(不自动跳转)
若需要拿到每一步的重定向地址,可设置maxRedirects: 0拦截自动跳转,通过响应头的Location字段获取下一跳地址:
async function trackAllRedirects(url) { let currentUrl = url; const redirectChain = []; while (true) { try { const response = await axios.get(currentUrl, { 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' } }); redirectChain.push(currentUrl); break; } catch (error) { if (error.response && [301, 302, 307, 308].includes(error.response.status)) { const nextUrl = error.response.headers.location; const absoluteNextUrl = new URL(nextUrl, currentUrl).href; redirectChain.push(currentUrl); currentUrl = absoluteNextUrl; } else { console.error('跟踪重定向中断:', error.message); break; } } } console.log('重定向轨迹:', redirectChain); return redirectChain; }
二、浏览器自动化方案(处理前端JS跳转/弹窗问题)
如果目标网站依赖前端JS触发跳转(非HTTP重定向),Axios无法捕获这类跳转,可使用Puppeteer模拟真实浏览器行为,同时拦截弹窗:
const puppeteer = require('puppeteer'); async function getRedirectByBrowser(initialUrl) { const browser = await puppeteer.launch({ headless: false }); // 设为false可可视化操作 const page = await browser.newPage(); // 自动拦截并关闭弹窗 page.on('dialog', async dialog => { console.log('拦截弹窗:', dialog.message()); await dialog.dismiss(); }); // 监听页面跳转事件 page.on('framenavigated', frame => { if (frame === page.mainFrame()) { console.log('当前页面URL:', frame.url()); } }); try { await page.goto(initialUrl, { waitUntil: 'networkidle2' }); const finalUrl = page.url(); console.log('最终重定向URL:', finalUrl); return finalUrl; } catch (error) { console.error('浏览器操作失败:', error.message); } finally { await browser.close(); } } getRedirectByBrowser('你的初始通用URL');
三、拆分项目的两步方案
若需要拆分流程,可按以下步骤执行:
- 第一步:解析初始页面
用Axios+Cheerio请求初始URL,提取页面内的表单参数、JS变量等跳转依赖数据。 - 第二步:模拟跳转逻辑
根据提取到的参数,构造跳转请求(Axios)或模拟点击操作(Puppeteer),获取最终重定向URL。
内容的提问来源于stack exchange,提问作者Benny
相关产品推荐
相关产品推荐

