【问题标题】:Scraper not returning any values with jquery using cheerio使用cheerio的jquery不返回任何值的刮板
【发布时间】:2016-01-03 23:56:26
【问题描述】:

尝试抓取网站 (www.ozbargain.com) 的首页以返回 a 标记中包含对 xbox 的引用但没有任何内容返回到控制台的任何内容。我认为问题在于带有 :contains 的 if 语句。

var fs = require('fs'),
    request = require('request'),
    cheerio = require('cheerio');

url = 'http://www.ozbargain.com.au';

request(url, function(error, response, html) {
  if (!error && response.statusCode == 200) {
    var $ = cheerio.load(html);
    if($("a:contains('Xbox')").length) {
      //console.log(this);
      var el = $(this);
      var log = el.text();
      console.log(log);
    } else {
      console.log('hey');
    }
  }
});

我要的 html 块。特别是,我想要一个标签;

<h2 class="title" id="title214252"><a href="/node/214252">Free on Xbox One, Xbox 360, PS3, PS4: Tales from the Borderlands (Episode 1)</a></h2>

【问题讨论】:

  • 您的选择器一定是错误的。在浏览器中打开控制台,看看是否选择了您期望的项目。
  • 这里是完整的html字符串。我将如何连接它以形成我的选择器? &lt;h2 class="title" id="title214252"&gt;&lt;a href="/node/214252"&gt;Free on Xbox One, Xbox 360, PS3, PS4: Tales from the Borderlands (Episode 1)&lt;/a&gt;&lt;/h2&gt;

标签: javascript jquery node.js web-scraping cheerio


【解决方案1】:

包含的 Cheerio 语法与 jQuery 略有不同。省略您正在搜索的字符串周围的单引号,它应该可以工作:

$("a:contains(Xbox)")

【讨论】:

    【解决方案2】:

    将选择器分配给一个变量,然后调用文本方法。

    request(url, function(error, response, html) {
        if (!error && response.statusCode == 200) {
            var $ = cheerio.load(html);
            var $el = $("a:contains('Xbox')");
    
            if ($el.length) {
                console.log($el.text());
            } else {
                console.log('hey');
            }
        }
    });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-08-10
      • 1970-01-01
      • 2014-08-31
      • 1970-01-01
      • 1970-01-01
      • 2012-09-26
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多