如何通过x-ray / 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个标题缺少评论的信息......
任何有用的帮助
答案 0 :(得分:4)
由于存在no way to reference the current context in a CSS selector,因此使用X-ray
包很容易抓取标记。这对于获取tr
行之后的下一个tr.thing
兄弟来获取评论非常有用。
我们仍然可以使用"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' } ]