nodejs 爬虫 axios 异步爬虫 教程 【一】

axios 自定义headers

javascript 复制代码
axios.defaults.headers.common["User-Agent"] =

  "Googlebot/2.1 (+http://www.google.com/bot.html)";

运行环境:

node :v18

javascript 复制代码
const axios = require("axios");
axios.defaults.headers.common["User-Agent"] =
  "Googlebot/2.1 (+http://www.google.com/bot.html)";

async function crawler() {
  try {
    let task = [];
    console.log(new Date().getTime());
    console.time("run");

    for (let i = 1; i < 100; i++) {
      const url = `https://licai.cofool.com/ask/new-${i}.html`;
      const response = await axios.get(url);
      task.push(response);
    }

    const result = await Promise.all(task);
    for (let item of result) {
      ret_obj = item.data.length;
      console.log(ret_obj);
    }
    console.timeEnd("run");
    console.log(new Date().getTime());
  } catch (error) {
    console.error(error);
  }
}
for (let j = 0;; j++) {
  crawler();
}

程序不断遍历翻页url,从第一页到100页。然后是一个死循环。 要控制次数,可以在最后一行修改:

javascript 复制代码
for (let j = 0; j<100; j++) {
  crawler();
}

程序没有做解析html的功能,首先调试通过后,会输出获取的html的文档大小。

下一节课我们会带大家去解析html的内容。

相关推荐
十五年专注C++开发几秒前
CMake进阶:find_package使用总结
开发语言·c++·cmake·跨平台编译
lxw18449125141 分钟前
PHP凉了?岗位缩水50%+,开发者该何去何从?
开发语言·php
Clarence Liu9 分钟前
用 Go 从 100 亿个数中找到最小的 100 个数 —— 实战与原理
开发语言·后端·golang
xiaowu08015 分钟前
IEnumerable、IEnumerator接口与yield return关键字的相关知识
java·开发语言·算法
csbysj202020 分钟前
Perl 目录操作指南
开发语言
-To be number.wan21 分钟前
C++ 运算符重载入门:让“+”也能为自定义类型服务!
开发语言·c++
未来之窗软件服务21 分钟前
幽冥大陆(七十九)Python 水果识别训练视频识别 —东方仙盟练气期
开发语言·人工智能·python·水果识别·仙盟创梦ide·东方仙盟
王家视频教程图书馆26 分钟前
android java 开发网路请求库那个好用请列一个排行榜
android·java·开发语言
POLITE335 分钟前
Leetcode 238.除了自身以外数组的乘积 JavaScript (Day 7)
前端·javascript·leetcode
小宇的天下42 分钟前
Calibre Introduction to Calibre 3DSTACK(1)
开发语言