Get page title with cheerio

I am trying to get title url tag with cheerio. But I get empty string values. This is my code:

app.get('/scrape', function(req, res){

    url = 'http://nrabinowitz.imtqy.com/pjscrape/';

    request(url, function(error, response, html){
        if(!error){
                        var $ = cheerio.load(html);

            var title, release, rating;
            var json = { title : "", release : "", rating : ""};

            $('title').filter(function(){
                //var data = $(this);
                var data = $(this);
                        title = data.children().first().text();            
                        release = data.children().last().children().text();

                json.title = title;
                json.release = release;
            })

            $('.star-box-giga-star').filter(function(){
                var data = $(this);
                rating = data.text();

                json.rating = rating;
            })
        }


        fs.writeFile('output.json', JSON.stringify(json, null, 4), function(err){

            console.log('File successfully written! - Check your project directory for the output.json file');

        })

        // Finally, we'll just send out a message to the browser reminding you that this app does not have a UI.
        res.send('Check your console!')
    })
});
+4
source share
2 answers
request(url, function (error, response, body) 
{
  if (!error && response.statusCode == 200) 
  {
    var $ = cheerio.load(body);
    var title = $("title").text();
  }
})

Using Javascript, we extract the text contained in the title tags.

+12
source

If Robert Ryan’s solution still doesn’t work, I would be suspicious of the formatting of the original page, which may be somehow distorted.

gzip , , Cheerio . , HTML.

0

Source: https://habr.com/ru/post/1538292/


All Articles