使用cheerio获取页面的标题

我试图得到与cheerio的URL的标题标签。 但是,我得到空string值。 这是我的代码:

app.get('/scrape', function(req, res){ url = 'http://nrabinowitz.github.io/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!') }) }); 

 request(url, function (error, response, body) { if (!error && response.statusCode == 200) { var $ = cheerio.load(body); var title = $("title").text(); } }) 

使用JavaScript,我们提取“标题”标签中包含的文本。

如果罗伯特·瑞安的解决scheme仍然无法正常工作,我会怀疑原始页面的格式,这可能会以某种方式变形。

在我的情况下,我接受gzip和其他压缩,但从来没有解码,所以Cheerio试图parsing压缩的二进制位。 当控制台logging原始的身体,我能够发现二进制文本,而不是纯文本的HTML。

Interesting Posts