我已经使用请求模块登录到站点并导航到包含一些要打印到控制台的数据的页面,如果我在浏览器中的页面上,并将此代码放入控制台,则数据打印出我想要的样子。
Array.from($("tbody")[0].children).forEach((el, index) => {
if (index % 2 == 0) {
console.log(el.children[1].textContent);
}
});
这是相关代码
const request = require('request-promise').defaults({ jar : true });
const cheerio = require('cheerio');
const my_site = 'https://example.com';
const html = await request.get(my_site);
const $ = cheerio.load(html);
Array.from($("tbody")[0].children).forEach((el, index) => {
if (index % 2 == 0) {
console.log(el.children[1].textContent);
}
});
运行上面的代码将返回错误
TypeError: Cannot read property '1' of undefined
at Array.from.forEach (/home/meano/Desktop/serverless/utils/scrape.js:30:36)
at Array.forEach (<anonymous>)
at main (/home/meano/Desktop/serverless/utils/scrape.js:28:44)
答案 0 :(得分:0)
这给了我我想要的数据
const html = await request.get(my_site);
const $ = cheerio.load(html);
let body = $("tbody").text()
console.log(body)