首页 > 解决方案 > 为什么我的 for 循环不能按预期工作?运行函数两次 - JavaScript

问题描述

所以伙计们,我有抓取功能,在这里我创建抓取数据的对象。刮板代码为:

const axios = require('axios');
const cheerio = require('cheerio');

const db = require('../config/db.config');
const Article = db.article;

const prices = new Array();
const ids = new Array();
const descs = new Array();
const links = new Array();
for (p = 1; p < 3; p++) {
  function again() {
    const url = `https://www.olx.ba/pretraga?vrsta=samoprodaja&kategorija=23&sort_order=desc&kanton=9&sacijenom=sacijenom&stranica=${p}`;

    axios
      .get(url)
      .then((response) => {
        let $ = cheerio.load(response.data);
        $('div[class="naslov"] > a').each((i, el) => {
          const id = $(el).attr('href'); // ID, description and link are in the same div class
          const desc = id;
          const link = id;
          descs.push(desc.substring(36)); //Retriving description with substring and push into array
          ids.push(id.substring(27, 35)); //Retriving id with substring and push into array
          links.push(link); //Retriving link and push into array
          for (var i = 0; i < descs.length; i++) {
            descs[i] = descs[i].replace('/', '').replace('-', ' ');
          }
        });
        $('div[class="datum"] > span').each((i, el) => {
          $('span[class="prekrizenacijena"]').remove();
          const price = $(el).text();
          prices.push(price); //Retriving price and push into array
        });
        for (var i = prices.length - 1; i >= 0; i--) {
          if (prices[i] === 'PO DOGOVORU') {
            prices.splice(i, 1);
          }
        }

        async function asy() {
          const sqm = new Array();
          for (k = 0; k < links.length; k++) {
            const res = await axios
              .get(`${links[k]}`)
              .then((result) => {
                let $ = cheerio.load(result.data);
                const pr = $('div[class="df2  "]').first().text();
                sqm.push(pr);
                for (var i = 0; i < sqm.length; i++) {
                  sqm[i] = sqm[i].replace('m2', '');
                }
              })
              .catch((err) => {
                //handle error
                console.log(err);
              });
          }

          const object = ids.map((element, index) => {
            const ppm2 =
              parseFloat(
                prices[index].replace(/\.| ?€$/g, '').replace(',', '.')
              ) / parseFloat(sqm[index]);
            const ppm2final = Math.round(ppm2);
            return {
              id: element,
              price: prices[index],
              descr: descs[index],
              link: links[index],
              sqm: sqm[index],
              ppm2: ppm2final + ' KM',
            };
          });

          console.log(object);
          console.log(Object.keys(object).length);

          /*const ins = await Article.bulkCreate(object)
        .then(console.log('Data added to DB'))
        .catch((err) => console.log(err));*/
        }
        asy();
      })
      .catch((e) => {
        console.log(e);
      });
  }
  again();
}

现在,当我删除第一个forlopfunction again()而不是插入时${p},例如。url1,2,3 等它工作完美 - 获取 sqm 以获得正确的链接。

现在的问题:我想多次运行这个 url,因为${p}那个 url 上的页面数。现在我遇到的第一个问题:

  1. sqm 不正确 - sqm 数据被抛出整个对象并且对于该链接不正确。(当我不使用时它是正确的${p}
  2. 我第一次获得 sqm 数据(但该链接不正确),当函数需要第二次运行时(对于第二页 - 到 ${p}=2) - sqm 根本没有被获取(它抛出 NaN)。

我也有console.log(Object.keys(object).length);我期望第一次是 30 的地方,然后第二次运行后我得到 60。(每页包含 30 篇文章),但我得到 60,然后又是 60。

我已经尝试了很多东西:异步函数,将 axios 置于 await 等,但没有什么真正起作用 - 有时我只得到 30 篇文章,有时是 60 篇但值不正确。

标签: javascript

解决方案


推荐阅读