【发布时间】:2019-03-12 10:19:03
【问题描述】:
分配是一个命令行节点应用程序,它从特定站点刮取一些数据并将该数据保存到 CSV 文件中。
我正在使用scrape-it 来抓取数据并成功获取我需要的所有数据,但我正在努力弄清楚如何将每个 URL(存储在 urls 中)添加到它们相应的衬衫对象中,即一个对象数组。
这是我目前所拥有的。
const scrapeIt = require("scrape-it");
const mainURL = "http://shirts4mike.com/";
scrapeIt(`${mainURL}shirts.php`, {
pages: {
listItem: ".products li",
name: "pages",
data: {
url: {
selector: "a",
attr: "href"
}
}
}
})
.then(({ data }) => {
const urls = data.pages.map(page => `${mainURL}${page.url}`);
console.log(urls);
const shirtCalls = urls.map(url =>
scrapeIt(url, {
name: {
selector: ".shirt-picture img",
attr: "alt"
},
image: {
selector: ".shirt-picture img",
attr: "src"
},
price: {
selector: "span.price"
}
})
);
return Promise.all(shirtCalls);
})
.then(shirtResults => {
const shirts = shirtResults.map(shirtResult => shirtResult.data);
console.log(shirts);
});
所以“衬衫”给我的输出是,
[ { name: 'Logo Shirt, Red',
image: 'img/shirts/shirt-101.jpg',
price: '$18' },
{ name: 'Mike the Frog Shirt, Black',
image: 'img/shirts/shirt-102.jpg',
price: '$20' },
{ name: 'Mike the Frog Shirt, Blue',
image: 'img/shirts/shirt-103.jpg',
price: '$20' },
{ name: 'Logo Shirt, Green',
image: 'img/shirts/shirt-104.jpg',
price: '$18' },
{ name: 'Mike the Frog Shirt, Yellow',
image: 'img/shirts/shirt-105.jpg',
price: '$25' },
{ name: 'Logo Shirt, Gray',
image: 'img/shirts/shirt-106.jpg',
price: '$20' },
{ name: 'Logo Shirt, Teal',
image: 'img/shirts/shirt-107.jpg',
price: '$20' },
{ name: 'Mike the Frog Shirt, Orange',
image: 'img/shirts/shirt-108.jpg',
price: '$25' } ]
但我想让最终结果看起来像......
[ { name: 'Logo Shirt, Red',
image: 'img/shirts/shirt-101.jpg',
price: '$18',
url: 'http://shirts4mike.com/shirt.php?id=101' //which is at urls[0]
},
{ name: 'Mike the Frog Shirt, Black',
image: 'img/shirts/shirt-102.jpg',
price: '$20',
url: 'http://shirts4mike.com/shirt.php?id=102' //urls[1]
}, //...etc etc
希望这一切都说得通,对于 Promise(和节点)来说仍然很新,所以我感觉有点超出我的深度。提前谢谢!
【问题讨论】:
-
感谢您的建议。我想尝试在最后的 .then() 块中执行此操作吗?
标签: javascript node.js npm web-scraping es6-promise