【发布时间】:2019-03-25 09:54:12
【问题描述】:
我有一个代码,它可以对特定页面进行网络报废。我使用 puppeteer+cheerio 来做到这一点。在我的笔记本电脑上,代码完美运行。但在将其部署到 VDS 后,cheerio each() 选择器开始工作异常。 (但它在我的笔记本电脑上仍然可以正常工作)。问题是在 VDS 上出现以下错误:
(node:28544) UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'trim' of undefined 在节点。 (/home/ubuntu/handbot/liveMonitoring.js:211:82) 在 initialize.exports.each (/home/ubuntu/handbot/node_modules/cheerio/lib/api/traversing.js:300:24) 在节点。 (/home/ubuntu/handbot/liveMonitoring.js:182:29) 在 initialize.exports.each (/home/ubuntu/handbot/node_modules/cheerio/lib/api/traversing.js:300:24) 在 liveMonitoring (/home/ubuntu/handbot/liveMonitoring.js:175:28) 在 process._tickCallback (internal/process/next_tick.js:68:7) (节点:28544)UnhandledPromiseRejectionWarning:未处理的承诺拒绝。此错误源于在没有 catch 块的情况下抛出异步函数内部,或拒绝未使用 .catch() 处理的承诺。 (拒绝编号:1) (节点:28544)[DEP0018] DeprecationWarning:不推荐使用未处理的承诺拒绝。将来,未处理的 Promise 拒绝将使用非零退出代码终止 Node.js 进程。
最有趣的一点是,有时错误会消失(似乎没有发生错误的模式)。 我试图通过重新安装 node js 来解决这个问题,但它没有用。问题不在我的代码中(因为它可以在我的笔记本电脑上运行,有时甚至可以在 vds 上运行)。我认为每个()函数的导出都有一些问题。由于错误消息,有一些错误发生在
/home/ubuntu/handbot/node_modules/cheerio/lib/api/traversing.js:300:24
traversing.js的代码(298-302行):
`
exports.each = function(fn) {
var i = 0, len = this.length;
while (i < len && fn.call(this[i], i,
this[i]) !== false) ++i;
return this;
};
导致错误的代码:
const page = await browser.newPage();
await page.goto(url, {timeout:0}).catch((err)=> { console.log(err)});
await page.setRequestInterception(true);
page.on('request', req => {
if(['image', 'stylesheet', 'font'].indexOf(req.resourceType()) !== -1)
req.abort();
else
req.continue();
});
let content = await page.content();
let $ = cheerio.load(content);
let gameContent=$('#games_content').children('div').children('div');
gameContent.children().each(function(i, elem1){
let league=$(elem1).children('.greenBack').children('.c-events__name').children('a').text().trim();
$(this).children().each(function(j, elem2){
if(j!==0) {
let currentInfo = {};
currentInfo['league'] = league;
let shortCut = $(elem2).children('.c-events__item_game').children('.c-events-scoreboard').children();
let mainInfo = shortCut.first();
currentInfo['link'] = mainInfo.children("a").attr("href");
let teams = mainInfo.children("a").children("span").attr("title").trim().split("—");
currentInfo['team1'] = teams[0].trim();
currentInfo['team2'] = teams[1].trim();
let shortCutForTotal = $(elem2).children('.c-events__item_game').children('.c-bets');
}
});
});
提前感谢您! `
【问题讨论】:
-
您是否阅读了这部分错误消息:
Cannot read property 'trim' of undefined at Node. (/home/ubuntu/handbot/liveMonitoring.js:211:82)我认为这个问题与each没有任何关系,它只是堆栈跟踪的一部分 -
是的,我做到了。但是我没有发现我的那部分代码有什么问题。最令人困惑的是,有时我的代码有效,有时会发生错误。所以我真的不知道该怎么做
-
我已经升级了帖子。感谢您的建议
标签: javascript node.js web-scraping deployment cheerio