nodejs | 看看豆瓣Top250电影有哪些?

117 阅读1分钟

前面写了Python 的版本,然后用 nodejs 页写一个吧!

思路

  • 需要知道一共有多少页
  • 爬单个页面数据处理
  • 分页爬取,循环一下单个页面数据处理就好了

代码

const axios = require("axios");
const cheerio = require("cheerio");
const fs = require("fs");
const dbUrl = "https://movie.douban.com/top250";
// 找到页数,每页25个
const findCount = async () => {
  try {
    const { status, data } = await axios.get(dbUrl);
    if (status === 200) {
      const $ = cheerio.load(data);
      const count = $(".count").text();
      return count.replace(/[^0-9]/gi, "");
    }
  } catch (error) {
    console.log("error", error.code);
    return 0;
  }
};

// 处理函数
const handleText = async (pageNum) => {
  const url = dbUrl + `?start=${pageNum}`;
  console.log(url);
  try {
    const { status, data } = await axios.get(url);
    let list = [];
    if (status === 200) {
      const $ = cheerio.load(data);
      const pic = $(".pic");
      for (let i = 0; i < pic.length; i++) {
        const element = pic[i];
        const $img = cheerio.load(element);
        const index = $img("em").text();
        const imgs = $img("img").attr();
        list.push({ index, name: imgs.alt, img: imgs.src });
      }
      return list;
    }
  } catch (error) {
    console.log("error", error.code);
    return [];
  }
};

const main = async () => {
  // 如果存在文件,则删除
  if (fs.existsSync("./douban.json")) {
    fs.unlinkSync("./douban.json");
  }
  let result = [];
  const count = (await findCount()) / 25;
  for (let i = 0; i < count; i++) {
    const listItem = await handleText(i * 25);
    result.push(...listItem);
  }
  //   追加文件
  fs.appendFileSync("./douban.json", JSON.stringify(result));
};

main();

结论

最后会在同一个文件夹下面生成一个douban.json的数组对象。

本文由mdnice多平台发布