2016-11-13 20 views
0

我試圖讓從「一」標籤的文本在這個網頁上的每個項目獲得的消息描述與Cheerio

https://hn.algolia.com/?query=apple&sort=byPopularity&prefix&page=0&dateRange=all&type=story

我已經解析了一些網頁,但我有這個問題,這是我的代碼。

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

request({ 
    method: 'GET', 
    url: 'https://hn.algolia.com/?query=apple&sort=byPopularity&prefix&page=0&dateRange=all&type=story' 
}, function(err, response, body) { 
if (err) return console.error(err); 

// Tell Cherrio to load the HTML 
$ = cheerio.load(body); 
// list = []; 
// $('div[id="item-main"]').each(function(){ 
// var href = $(this).find('div > div').attr('h2'); 
// list.push(h2); 
// }); 
$('item-title-and-infos').each(function() { 
    var href = $('h2', this).attr('href'); 
    if (href.lastIndexOf('/') > 0) { 
     console.log($('a', this).text()); 
    } 
}); 
}); 

感謝。

回答

0

問題是內容是異步加載的,首先加載一個幾乎空的頁面,然後加載你正在查找的內容。

只是CONSOLE.LOG您所查詢的身體,你會看到像somethig:

<!DOCTYPE html> 
<html ng-app='HNSearch'> 
<head ng-controller='HeadCtrl'> 
... 
links and meta 
... 
</head> 
<body> 
<div id='main' ng-cloak role='main' ui-view> 

! NO CONTENT HERE ! IT WILL BE LOADED AFTER 

</div> 
<script src="https://d3nb9u6x572n0.cloudfront.net/assets/application-70dfa2f5ecb75bc8dfaa8729257bcbf1.js"></script> 
</body> 
</html> 

如果您檢查谷歌瀏覽器的網頁,你會看到這個鏈接被調用後:

https://uj5wyc0l7x-dsn.algolia.net/1/indexes/Item_production/query?x-algolia-api-key=8ece23f8eb07cd25d40262a1764599b1&x-algolia-application-id=UJ5WYC0L7X&x-algolia-agent=Algolia%20for%20AngularJS%203.7.5 

所以最後我發現這個解決方案,可以HEP你:

request.post({ 
    url:'https://uj5wyc0l7x-dsn.algolia.net/1/indexes/Item_production/query?x-algolia-api-key=8ece23f8eb07cd25d40262a1764599b1&x-algolia-application-id=UJ5WYC0L7X&x-algolia-agent=Algolia%20for%20AngularJS%203.7.5', 
    body:'{"params":"query=apple&hitsPerPage=20&minWordSizefor1Typo=5&minWordSizefor2Typos=9&advancedSyntax=true&ignorePlurals=false&tagFilters=%5B%22story%22%5D&numericFilters=%5B%5D&page=0&queryType=prefixLast&typoTolerance=true&restrictSearchableAttributes=%5B%5D"}', 
    gzip:true, 
    headers:{ 
     accept:'application/json', 
     "Accept-Encoding":"gzip, deflate, br", 
     "Accept-Language":"es-ES,es;q=0.8", 
     "Cache-Control":"no-cache", 
     Connection:"keep-alive", 
     "Content-Length":258, 
     "content-type":"application/x-www-form-urlencoded", 
     Host:"uj5wyc0l7x-dsn.algolia.net", 
     Origin:"https://hn.algolia.com", 
     Pragma:"no-cache", 
     Referer:"https://hn.algolia.com/?query=apple&sort=byPopularity&prefix&page=0&dateRange=all&type=story", 
     "User-Agent":"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/55.0.2883.87 Safari/537.36" 
    } 
}, 
function (err,res,body) { 
    console.log(body); 
}); 

現在身體是一個巨大的JS打開包含所有數據的文件。 我跳這有助於你。