javascript - 在对象数组中插入新的键值对,但值是由 axios.get 创建的
问题描述
所以我一直在研究刮刀。一切都很好,直到我尝试为单个链接抓取数据。
现在解释一下:我有一个刮刀,它可以刮我关于公寓的数据。现在第一个 url 是文章所在的页面(应该获取大约 29-30)。现在在那个页面上我没有关于平方米的信息,所以我需要为每个被刮掉的链接运行另一个刮板,然后从那里刮掉平方米。
这是我拥有的代码:
const axios = require('axios');
const cheerio = require('cheerio');
const url = `https://www.olx.ba/pretraga?vrsta=samoprodaja&kategorija=23&sort_order=desc&kanton=9&sacijenom=sacijenom&stranica=2`;
axios.get(url).then((response) => {
const articles = [];
const $ = cheerio.load(response.data);
$('div[id="rezultatipretrage"] > div')
.not('div[class="listitem artikal obicniArtikal i index"]')
.not('div[class="obicniArtikal"]')
.each((index, element) => {
$('span[class="prekrizenacijena"]').remove();
const getLink = $(element).find('div[class="naslov"] > a').attr('href');
const getDescription = $(element)
.find('div[class="naslov"] > a > p')
.text();
const getPrice = $(element)
.find('div[class="datum"] > span')
.text()
.replace(/\.| ?KM$/g, '')
.replace(' ', '');
const getPicture = $(element)
.find('div[class="slika"] > img')
.attr('src');
articles[index] = {
id: getLink.substring(27, 35),
link: getLink,
description: getDescription,
price: getPrice,
picture: getPicture,
};
});
articles.map((item, index) => {
axios.get(item.link).then((response) => {
const $ = cheerio.load(response.data);
const sqa = $('div[class="df2 "]').first().text();
});
});
console.log(articles);
});
现在代码的第一部分就像它应该的那样,我一直在努力处理第二部分。
现在我正在映射,articles
因为对于每个链接,我需要将其加载到axios
函数中并获取有关平方米的数据。
因此,我想要的输出将是更新的文章:其中包含旧对象和关键值,但具有关键平方米和刮擦平方米的值。
关于如何实现这一目标的任何想法?谢谢!
解决方案
您可以简单地将有关平方米的信息添加到当前article
/item
中,例如:
const articlePromises = Promise.all(articles.map((item) => {
return axios.get(item.link).then((response) => {
const $ = cheerio.load(response.data);
const sqa = $('div[class="df2 "]').first().text();
item.sqm = sqa;
});
}));
articlePromises.then(() => {
console.log(articles);
});
请注意,在记录结果文章之前,您需要等待所有映射的 Promise 解决。另请注意,使用async/await
您可以将代码重写为更简洁,请参阅https://javascript.info/async-await。
推荐阅读
- python-3.x - TensorFlow 如何从 s3 字节流中读取文件
- microsoft-graph-api - 如何使用 msgraph-sdk-java 更新用户个人资料照片?
- reactjs - 如何将单个组件用作带有 react-native tabview 的新实例
- java - 我们可以在生产系统上免费使用 zulu jdk 1.8 吗?
- matlab - 如何在 Matlab/Simulink 中获取有关错误“来自非结构数组对象的结构内容引用”的详细信息?
- reactjs - 在 React 中导入引导 CSS 无法编译
- paw-app - 移除 Paw 中的所有 URL 参数
- java - 递归创建完整且完整的二叉树
- javascript - 菜单下拉 JQuery
- c++ - 如何使用 CMake 链接库