2016-03-25 2 views
1

x- ray/nodejsを使用してハッカーのニュース(https://news.ycombinator.com/)を削り取るにはどうすればよいですか?X線/ノード経由のハッカーニュースをスクラップ

enter image description here

私はそれから、このような何かを取得したいと思います:

[ 
    {title1, comment1}, 
    {title2, comment2}, 
    ... 
    {"‘Minimal’ cell raises stakes in race to harness synthetic life", 48} 
    ... 
    {title 30, comment 30} 
] 

ありニューステーブルがあるが、私はそれをこすりする方法を知らない... の記事のそれぞれをウェブサイトは3つの列で構成されています。これらは、それらに固有の親を持たない。

x("https://news.ycombinator.com/", "tr", [{ 
    title: [".deadmark+ a"], 
    comments: ".age+ a" 
}]) 

x("https://news.ycombinator.com/", { 
    title: [".deadmark+ a"], 
    comments: [".age+ a"] 
}) 

を第二のアプローチは、30名と29コメント-coutsを返します...私は:だから構造は、これまでのところ、私が試してみました。この

<tbody> 
    <tr class="spacer"> //Markup 1 
    <tr class="athing"> //Headline 1 ('.deadmark+ a' contains title) 
    <tr class>   //Meta Information 1 (.age+ a contains comments) 
    <tr class="spacer"> //Markup 2 
    <tr class="athing"> //Headline 2 ('.deadmark+ a' contains title) 
    <tr class>   //Meta Information 2 (.age+ a contains comments) 
    ... 
    <tr class="spacer"> //Markup 30 
    <tr class="athing"> //Headline 30 ('.deadmark+ a' contains title) 
    <tr class>   //Meta Information 30 (.age+ a contains comments) 

のように見えます30タイトルのうちコメントがない情報がないので、それらを一緒にマップする可能性はありません。

何か助けがありました

答えて

3

no way to reference the current context in a CSS selectorがあるので、X-rayパッケージでマークアップするのは簡単ではありません。これは、tr.thingの行の後に次のtr兄弟を取得してコメントを取得すると便利です。

"next sibling" notation+)を使用して次の行に移動できますが、オプションのコメントリンクをターゲットにする代わりに、完全な行テキストを取得して正規表現でコメント値を抽出します。コメントがない場合は、値を0に設定します。

完全な作業コード:

var Xray = require('x-ray'); 
var x = Xray(); 

x("https://news.ycombinator.com/", { 
    title: ["tr.athing .deadmark+ a"], 
    comments: ["tr.athing + tr"] 
})(function (err, obj) { 
    // extracting comments and mapping into an array of objects 
    var result = obj.comments.map(function (elm, index) { 
     var match = elm.match(/(\d+) comments?/); 
     return { 
      title: obj.title[index], 
      comments: match ? match[1]: "0" 
     }; 
    }); 
    console.log(result); 
}); 

現在出力します

[ { title: 'Follow the money: what Apple vs. the FBI is really about', 
    comments: '85' }, 
    { title: 'Unable to open links in Safari, Mail or Messages on iOS 9.3', 
    comments: '12' }, 
    { title: 'Gogs – Go Git Service', comments: '13' }, 
    { title: 'Ubuntu Tablet now available for pre-order', 
    comments: '56' }, 
    ... 
    { title: 'American Tech Giants Face Fight in Europe Over Encrypted Data', 
    comments: '7' }, 
    { title: 'Moving Beyond the OOP Obsession', comments: '34' } ] 
+0

も数にカウンターのコメントを変換して、エラーを処理するためには良いかもしれません –

関連する問題