2016-02-28 119 views
0

當試圖運行代碼時,我不斷收到錯誤$.find('.market_listing_item_name_block').each() - undefined不是一個函數,指向查找。我覺得這個發現是cheerio的一個功能?爲了公平起見,我不知道,如果我連這樣做的權利,這是我的代碼:Cheerio錯誤,undefined不是函數//這是正確的方法嗎?

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。

我是這樣做之前,鍍鉻的方式,爲:

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?我相信我明顯缺少了幾個步驟。任何幫助非常感謝,謝謝。

+0

可能會發現不返回一個對象,將有each'的'的方法之前,使用換行元素與$,讓您的查詢來回空。你確定這是一個正確的調用:'$ .find(「。market_listing_item_name_block」)'?它不應該像下面的代碼那樣:'$(r).find(「。market_listing_item_name_block」)'? – guessimtoolate

+0

做一個'console.log($。find(「。market_listing_item_name_block」));'並且看看它是否有方法。每個,並且在這裏粘貼結果 – Datsik

+0

@Datsik用$ .find做它仍然返回undefined不是一個函數,現在作爲guessimtoolate說,我試過$(r).find並返回一個對象。 https://i.gyazo.com/4eeb0a86cc7f3c351347c52c9503a9ab.png – Furdew

回答

1

當你得到一個元素,你需要做進一步選擇

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

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

    console.log(title) 
}) 
相關問題