我有一个非常简单的文件,应该抓取一些数据的单个网页。在四处阅读后,我把自己设置为R2,request和cheerio,但现在我被卡住了。这就是我到目前为止所拥有的代码。
request('http://www.ciclopi.eu/frmLeStazioni.aspx?ID=144', function (error, response, html) {
if (!error && response.statusCode == 200) {
var $ = cheerio.load(html);
artoo.bootstrap(cheerio);
var scraper = $('span.Stazione, span.TableComune, span.Red').scrape({
class: 'class',
content: 'text'
});
console.log(scraper);
}
});
这段代码将scraper变量解析为一个json对象,结构如下:
[ { class: 'Stazione', content: 'Galleria Gerace' },
{ class: 'TableComune', content: 'Via Carlo Matteucci' },
{ class: 'Red', content: '7 bici libere5 posti disponibili' },
{ class: 'Stazione', content: 'C. Marchesi' },
{ class: 'TableComune', content: 'Via M. Valgimigli' },
{ class: 'Red', content: '2 bici libere10 posti disponibili' },
{ class: 'Stazione', content: 'CNR-Praticelli' },
{ class: 'TableComune', content: 'Via G. Moruzzi' },
{ class: 'Red', content: '7 bici libere7 posti disponibili' } ]
我需要的是重新排列scraper对象,如下所示
scraper = [
{
"Name": the content for class Stazione,
"Address": the content for class TableComune,
"Bikes": the content for class Red
},
{
"Name": the content for class Stazione,
"Address": the content for class TableComune,
"Bikes": the content for class Red
}
...
]
我真的一无所知,希望我已经解释清楚了..
发布于 2018-08-16 04:52:24
对于这种突变,我会使用Array.prototype.reduce方法。
const data = [
{ class: 'Stazione', content: 'Galleria Gerace' },
{ class: 'TableComune', content: 'Via Carlo Matteucci' },
{ class: 'Red', content: '7 bici libere5 posti disponibili' },
{ class: 'Stazione', content: 'C. Marchesi' },
{ class: 'TableComune', content: 'Via M. Valgimigli' },
{ class: 'Red', content: '2 bici libere10 posti disponibili' },
{ class: 'Stazione', content: 'CNR-Praticelli' },
{ class: 'TableComune', content: 'Via G. Moruzzi' },
{ class: 'Red', content: '7 bici libere7 posti disponibili' }
];
const result = data.reduce((acc, item) => {
if (item.class === 'Stazione') {
acc.push({ 'Name': item.content });
} else {
const last = acc[acc.length - 1];
if (item.class === 'TableComune') {
last['Address'] = item.content;
} else { // if (item.class === 'Red')
last['Bikes'] = item.content;
}
}
return acc;
}, []);
在这里,我们遍历初始数据数组,并通过2个条件点生成结果数组:
如果当前项为,则我们将一个新对象推送到结果数组;此对象将具有与当前Stazione
内容将移动到Address属性,Red内容将移动到Bikes属性。
该过程仅在初始数据数组中Stazione-TableComune-Red对象的严格顺序的情况下才有效。
https://stackoverflow.com/questions/51847443
复制相似问题