NodeJS 从cheerio块获得空响应

lf5gs5x2  于 2023-01-01  发布在  Node.js
关注(0)|答案(1)|浏览(117)

我试图在Hello函数的另一个数组中获取描述数组数据,但我得到了一个错误,“无法读取未定义的属性长度”,而我已经控制了描述数组,它正在给我所需的数据。那么这个错误的原因可能是什么?

const unirest = require("unirest");
const cheerio = require("cheerio");

const data = async () => {
  var description = [];
  unirest
    .get("https://www.google.com/search?q=rotating proxies")
    .headers({ Accept: "application/json", "Content-Type": "application/json" })
    .proxy(
      "proxy"
    )//hided
    .then((response) => {
      const $ = cheerio.load(response.body);

      $(".uEierd").each((i, el) => {
        description[i] = $(el).find(".yDYNvb").text();
        console.log(description[i]);
        return description;
      });
    });
};
async function Hello() {
  var result2 = [];
  result2 = await data();
  for (let i = 0; i < result2.length; i++) {
    console.log(result2[i]);
  }
}
Hello();
zf2sa74q

zf2sa74q1#

两个问题:

  • 无法从data()函数返回unirest承诺链
  • 在错误的位置返回description.each忽略返回值; .then()是您要返回的位置)

下面是一个可能的解决方案:

const cheerio = require("cheerio");
const unirest = require("unirest");

const data = () => {
  return unirest
    .get("https://www.google.com/search?q=rotating proxies")
    .headers({
      Accept: "application/json",
      "Content-Type": "application/json",
    })
    .proxy("proxy")
    .then(response => {
      const $ = cheerio.load(response.body);
      const descriptions = [];

      $(".uEierd").each((i, el) => {
        descriptions.push($(el).find(".yDYNvb").text());
      });

      return descriptions;
    });
};

const hello = async () => {
  const results = await data();
  console.log(results);
};
hello();

相关问题