You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用axios和cheerio迭代抓取下一页链接返回undefined如何解决

问题修复方案

原代码错误原因

  • 初始定义的url使用const声明,属于常量,无法在while循环内重新赋值,运行时会直接报错
  • axios返回的是完整响应对象,你直接将响应对象传入cheerio.load,没有取出响应体的data属性,导致cheerio无法正常解析页面DOM,因此获取下一页链接时返回undefined

修复后可运行代码

const axios = require("axios");
const cheerio = require("cheerio");

const base = "https://stackoverflow.com";
// 把const改成let,允许后续修改url值
let url = "https://stackoverflow.com/questions/tagged/web-scraping";
// 抽离公共请求配置,避免重复书写
const requestOpts = {
  headers: {
    "User-Agent": "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/88.0.4324.150 Safari/537.36"
  }
}

async function main(){
  let nextPage = ''
  // 首次请求
  let res = await axios.get(url, requestOpts);
  // 取响应体的data属性传入cheerio
  const $ = cheerio.load(res.data);
  nextPage = $('a[rel="next"]').eq(0).attr("href");
  console.log(nextPage);
  
  while(nextPage){
    url = base + nextPage;
    res = await axios.get(url, requestOpts);
    const $ = cheerio.load(res.data);
    nextPage = $('a[rel="next"]').eq(0).attr("href");
    console.log(nextPage);
  }
}

main();

内容的提问来源于stack exchange,提问作者SMTH

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.02 03:18:03