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的内容。

相关推荐
你不是我我33 分钟前
【Java 开发日记】SQL 语句左连接右连接内连接如何使用,区别是什么?
java·javascript·数据库
ghie909036 分钟前
C#语言中使用“using“关键字的介绍
开发语言·c#
七夜zippoe1 小时前
Java性能调优工具篇:JMH基准测试与Profiler(JProfiler/Async-Profiler)使用指南
java·开发语言·jprofiler·jmh·async-profiler
一壶浊酒..1 小时前
请求签名(Request Signature)
javascript
小龙报1 小时前
《嵌入式成长系列之51单片机 --- Keil5创建工程》
c语言·开发语言·c++·单片机·嵌入式硬件·51单片机·学习方法
无限进步_2 小时前
【C语言】贪吃蛇游戏设计思路深度解析:从零开始理解每个模块
c语言·开发语言·c++·git·游戏·github·visual studio
听风吟丶2 小时前
Java 函数式编程深度实战:从 Lambda 到 Stream API 的工程化落地
开发语言·python
rainFFrain2 小时前
qt显示类控件--- Label
开发语言·qt
渡我白衣2 小时前
深入理解 OverlayFS:用分层的方式重新组织 Linux 文件系统
android·java·linux·运维·服务器·开发语言·人工智能
西游音月2 小时前
(6)框架搭建:Qt实战项目之主窗体快捷工具条
开发语言·qt