Reputation: 2703
While following a tutorial about web scraping in Node JS, I ran into this problem when running this script in the terminal:
Object #<Object> has no method 'attr'
Here's the script I'm using:
var request = require('request'),
cheerio = require('cheerio'),
urls = [];
request('http://www.reddit.com', function (err, resp, body) {
if (!err && resp.statusCode == 200) {
var $ = cheerio.load(body);
$('a.title', '#siteTable').each(function() {
var url = this.attr('href');
urls.push(url)
});
console.log(urls);
}
});
Any ideas on how to fix this script so it doesn't throw an error? Any help would be really appreciated!
Upvotes: 2
Views: 842
Reputation: 191789
The scope object this
is not a jQuery object by default.
var url = this.getAttribute("href");
// or
var url = $(this).attr("href");
Upvotes: 3