如何使用 cheerio 访问对象内属性的值
how do I access the value of an attribute inside an object using cheerio
我正在尝试使用 cheerio 将属性 ("data-code") 的值推送到数组中。但是,我不断收到错误消息 "allAs[i].attr is not a function"
这是我目前所拥有的
const express = require('express');
const request = require('request');
const cheerio = require('cheerio');
const app = express();
app.get('/scrape', (req, res) => {
const url = 'http://store.emart.com/branch/list.do?id=1702';
request(url, (err, response, body) => {
if(!err) {
var idList = [];
console.log(typeof(idList));
var $ = cheerio.load(body);
var allAs = $("a").filter("[data-code]");
console.log(allAs[0].val);
for(var i = 0; i < allAs.length; i++){
//console.log(allAs[i]);
idList.push(allAs[i].attr("[data-code]"));
}
console.log();
res.send(body);
} else {
console.log("problems yo");
}
});
});
app.listen(3000, () => {
console.log("Server is up and running!!!");
});
应该有 330 个结果被推送到 idList。
根据您的代码,将此更改为:
idList.push(allAs[i].attr("[data-code]"));
...到...
idList.push(allAs[i].attribs['data-code']);
—
* 自从我上次使用 cheerio 以来已经有一段时间了,所以我不确定这是应该的还是一个错误。
我正在尝试使用 cheerio 将属性 ("data-code") 的值推送到数组中。但是,我不断收到错误消息 "allAs[i].attr is not a function"
这是我目前所拥有的
const express = require('express');
const request = require('request');
const cheerio = require('cheerio');
const app = express();
app.get('/scrape', (req, res) => {
const url = 'http://store.emart.com/branch/list.do?id=1702';
request(url, (err, response, body) => {
if(!err) {
var idList = [];
console.log(typeof(idList));
var $ = cheerio.load(body);
var allAs = $("a").filter("[data-code]");
console.log(allAs[0].val);
for(var i = 0; i < allAs.length; i++){
//console.log(allAs[i]);
idList.push(allAs[i].attr("[data-code]"));
}
console.log();
res.send(body);
} else {
console.log("problems yo");
}
});
});
app.listen(3000, () => {
console.log("Server is up and running!!!");
});
应该有 330 个结果被推送到 idList。
根据您的代码,将此更改为:
idList.push(allAs[i].attr("[data-code]"));
...到...
idList.push(allAs[i].attribs['data-code']);
—
* 自从我上次使用 cheerio 以来已经有一段时间了,所以我不确定这是应该的还是一个错误。