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

使用axios配合cheerio时报错cheerio.load() expects a string如何修复

错误原因
  • axios.get() 是异步请求方法,执行后返回的是 Promise 实例而非直接的请求响应对象,你代码里直接取resp.data得到的是undefined,cheerio.load接收到非字符串的undefined就会抛出对应报错。
  • 异步方法没有做异步流程处理,同步执行的逻辑会在请求返回前就执行完毕,就算没报错也拿不到爬取结果。
修复方法

推荐用async/await的写法处理异步逻辑,修复后代码如下:

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

const startLink = 'https://old.reddit.com/r/programming/';

// 函数前面加async标记为异步函数
const getPostTitles = async (link) => {
        // 请求前加await等待异步请求返回响应结果
        const resp = await axios.get(link, {
            // 可选配置:加User-Agent避免被reddit反爬拦截返回429错误
            headers: {
                'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36'
            }
        });
        const $ = cheerio.load(resp.data);
        const postTitles = [];

        $('div > p.title > a').each((_idx, el) => {
            const postTitle = $(el).text()
            postTitles.push(postTitle)
        });

        return postTitles;
};

// 调用异步函数要用then拿返回结果,或者在外层再加async函数用await取
getPostTitles(startLink).then(results => {
    console.log(results);
}).catch(err => {
    // 加错误捕获方便排查问题,比如网络失败、反爬拦截等
    console.error('爬取失败:', err.message);
});

如果习惯用Promise链式调用,也可以写成:

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

const startLink = 'https://old.reddit.com/r/programming/';

const getPostTitles = (link) => {
    return axios.get(link, {
        headers: {
            'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36'
        }
    }).then(resp => {
        const $ = cheerio.load(resp.data);
        const postTitles = [];
        $('div > p.title > a').each((_idx, el) => {
            postTitles.push($(el).text())
        });
        return postTitles;
    })
};

getPostTitles(startLink)
    .then(console.log)
    .catch(err => console.error('爬取失败:', err.message));

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.03 17:36:03