2017-07-15 36 views
0

我試圖在URL變量中的頁面上標記li標籤中包含的URL。它應該很簡單,但我無法讓它工作。我得到正確數量的元素,但它們都是空白的。 text()返回''& html()返回null。我在這裏做錯了什麼?NodeJS Cheerio Scraping li標籤總是返回NULL

const cheerio = require('cheerio'); 
const request = require('request'); 

function getHistory(){ 
    let url = 'http://coinmarketcap.com/historical/'; 
    request(url,(error,response,html)=>{ 
    var $ = cheerio.load(html); 
    $('li.text-center').each((i,element)=>{ 
     var omg = $(this).html(); 
     console.log(omg); 
    }); 
    }); 
} 

回答

1

與實際的jQuery,cheerio顯然不成立的this值。如果更改此:

var omg = $(this).html(); 

這樣:

var omg = $(element).html(); 

您將看到您所期望的HTML。


如果你真正想要的是href,那麼你應該針對<a>標籤與你的選擇,並從中獲得實際href屬性。你可以這樣做:

function getHistory(){ 
    let url = 'http://coinmarketcap.com/historical/'; 
    request(url,(error,response,html)=>{ 
    let $ = cheerio.load(html); 
    $('li.text-center a').each((i,element)=>{ 
     let omg = $(element).attr('href'); 
     console.log(omg); 
    }); 
    }); 
} 
+0

謝謝你的朋友,你救了我幾個小時的挫折! – Raven

+0

OMG,非常有幫助! –