通过X射线/节点刮黑客新闻

我怎么能通过X射线/ nodejs刮黑客新闻( https://news.ycombinator.com/ )?

在这里输入图像说明

我想从中得到这样的东西:

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

有一个新闻表,但我不知道如何刮…每个网站上的故事由三列组成。 这些没有一个是他们独一无二的父母。 所以结构看起来像这样

 <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) 

到目前为止我已经尝试过:

 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个评论…我不认为有任何可能将他们映射在一起,因为没有任何信息30个标题中的哪一个缺less评论…

任何帮助appriciated

由于在CSSselect器中没有办法引用当前的上下文,所以标记不容易被X-ray包所刮擦。 在tr.thing行之后得到下一个tr兄弟来获得注释将是有用的。

我们仍然可以使用“下一个兄弟”符号 ( + )到达下一行,但是不是定位可选的注释链接,而是抓取完整的行文本,然后使用正则expression式提取注释值。 如果不存在任何评论,则将该值设置为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' } ]