【问题标题】:Get title of a page with cheerio使用cheerio获取页面标题
【发布时间】:2014-04-27 17:25:39
【问题描述】:

我正在尝试使用cheerio 获取网址的标题标签。但是,我得到了空字符串值。这是我的代码:

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!')
    })
});

【问题讨论】:

  • 您没有处理 if (err) 情况,请确保添加此内容并检查是否是错误情况。

标签: javascript node.js express cheerio


【解决方案1】:
request(url, function (error, response, body) 
{
  if (!error && response.statusCode == 200) 
  {
    var $ = cheerio.load(body);
    var title = $("title").text();
  }
})

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

【讨论】:

  • 我正在使用它并且效果很好:$('head > title').text();
【解决方案2】:

如果 Robert Ryan 的解决方案仍然不起作用,我会怀疑原始页面的格式,这可能会以某种方式出现格式错误。

在我的情况下,我接受 gzip 和其他压缩但从不解码,所以 Cheerio 试图解析压缩的二进制位。在控制台记录原始正文时,我能够发现二进制文本而不是纯文本 HTML。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-09-08
    • 2012-01-20
    • 2010-12-06
    • 2021-02-23
    • 1970-01-01
    • 2010-11-06
    • 1970-01-01
    相关资源
    最近更新 更多