I'm trying to push the values of an attribute("data-code") into an array using cheerio. However, I keep getting the error message "allAs[i].attr is not a function"
Here's what I have so far
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!!!");
});
There should be 330 results pushed into idList.
Based on your code, change this:
idList.push(allAs[i].attr("[data-code]"));
... to ...
idList.push(allAs[i].attribs['data-code']);
—
* It's been a while since I last used cheerio so I'm not sure if this is how it's supposed to be or it's a bug.