【问题标题】:Cheerio error, undefined not a function // Is this the correct way?Cheerio 错误,未定义不是函数 // 这是正确的方法吗?
【发布时间】:2016-02-28 08:42:40
【问题描述】:

尝试运行代码时,我不断收到错误$.find('.market_listing_item_name_block').each() - undefined is not a function,指向 find。我以为 find 是cheerio 中的一个功能?公平地说,我不确定我是否做得对,这是我的代码:

var cheerio = require('cheerio')
$ = cheerio.load('#searchResultsRows')
var url = 'http://steamcommunity.com/market/search?appid=730'
xhr.get(url).success(function(r){
    $.find(".market_listing_item_name_block").each(function(){
        var name = $(this).find(".market_listing_item_name").text();
        console.log(name)
    })
})

xhr 是一个本质上类似于 AJAX 的对象。

我之前在 chrome 中的做法是:

var url = 'http://steamcommunity.com/market/search?appid=730'
var itemDiv = $("<div></div>")
$.get(url).success(function(r){
    d = $(r).find('#searchResultsRows')
    itemDiv.append(d)
})

然后:

itemDiv.find(".market_listing_item_name_block").each(function(){
   var name = $(this).find(".market_listing_item_name").text();
   console.log(name) // would normally do other things, but for the purpose of this post, i'm just console logging the name
})

我如何能够在节点/cheerio 中重新创建 ^?我相信我显然错过了几个步骤。非常感谢任何帮助,谢谢。

【问题讨论】:

  • 可能 find 不会返回具有each 方法的对象,因此您的查询返回为空。你确定这是一个正确的调用:$.find(".market_listing_item_name_block")?不应该是类似下面的代码:$(r).find(".market_listing_item_name_block")
  • 做一个console.log($.find(".market_listing_item_name_block"));,看看有没有方法.each,也把结果贴在这里
  • @Datsik 使用 $.find 仍然返回 undefined 不是一个函数,现在正如 guessimtoolate 所说,我尝试了 $(r).find 并返回了一个对象。 i.gyazo.com/4eeb0a86cc7f3c351347c52c9503a9ab.png

标签: node.js cheerio


【解决方案1】:

当你得到一个元素时,你需要在做进一步的选择之前用$包裹那个元素

const $ = Cheerio.load(body)
const list = $('div.titles li')

list.each((index, li) => {
  const title = $(li).find('p.title').text()

  console.log(title)
})

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-01-20
    • 2014-08-03
    • 2012-05-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多