Cheerio 没有在 Axios get request 中加载 HTML - 所有这些都在一个 aysnchrono



我正在研究Alexa技能的意图,该技能将成为新闻网站的头条新闻。我的代码在节点 js 中,托管在 AWS Lambda 上。 我正在使用 axios 和 cheerio 进行网络抓取,当我从命令行在本地机器上运行它们时,代码成功检索 HTML,cheerio 能够获得我需要的数据。 但是,当我在 Lambda 上运行代码时,每次我尝试使用 cheerio 加载 HTML 时都会抛出错误。

有趣的是,我尝试像这样用 cheerio 加载一个"html 字符串":

const $ = cheerio.load('<h2 class="title">Hello world</h2>');

我能够使用它并在 lambda 上获取我需要的数据。但是,如果我从 axios 中检索 html,并尝试使用 cheerio 加载它,它会抛出错误。 这是我发出的不起作用的调用:

const $ = cheerio.load(response.data);

我的代码如下:

"use strict";
const axios = require('axios');
const cheerio = require('cheerio');
const url = "https://news.ycombinator.com";
const newsHandler = {
"newsIntent": async function () {
var speechOutput = "";
axios.get(url)
.then(response => {
data = [];
const $ = cheerio.load(response.data);
$("table.itemlist tr td:nth-child(3)").each((i, elem) => {
data.push(
$(elem).text().trim()
);
});
for (const headline of data) {
speechOutput += headline + " ";
}
this.emit(":tell", speechOutput);
})
.catch(error => {
console.log(error);
})
}
}
module.exports = newsHandler;

它应该能够解析从 Axios 检索到的 HTML,使用所描述的选择器解析所有元素,并将其文本添加到数据数组中。 然而,即使只是写下这一行:

const $ = cheerio.load(response.data);

导致错误。请帮忙!

检查您的 lambda 超时并尝试增加它。

同样的情况也发生在我身上,它正在制作一个带有在 aws lambda 上运行的节点的抓取器,我遇到的问题是函数因超时而结束。

首先我使用JSDOM,然后使用两个库,我遇到了同样的问题。

解决方案是增加 lambda 超时(我的只有 3 秒),我将其增加到 10 秒,它工作得很好。之后,我发现抓取单个 URL 的整个功能大约需要 5 秒。

相关内容

最新更新