문제

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!

도움이 되었습니까?

해결책

The scope object this is not a jQuery object by default.

var url = this.getAttribute("href");
// or
var url = $(this).attr("href");
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top