首页 > 解决方案 > 在对象数组中插入新的键值对,但值是由 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函数中并获取有关平方米的数据。

因此,我想要的输出将是更新的文章:其中包含旧对象和关键值,但具有关键平方米和刮擦平方米的值。

关于如何实现这一目标的任何想法?谢谢!

标签: javascriptnode.jsaxios

解决方案


您可以简单地将有关平方米的信息添加到当前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


推荐阅读