溫馨提示×

js爬蟲怎樣控制爬取速度

js
小樊
97
2024-11-26 16:52:24
欄目: 編程語言

在JavaScript中,可以使用setTimeout函數來控制爬蟲的速度。setTimeout函數允許你在指定的毫秒數后執行一個函數。為了控制爬蟲速度,你可以在每次爬取網頁后使用setTimeout函數設置一個延遲。

以下是一個簡單的示例,展示了如何使用setTimeout控制爬蟲速度:

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

// 爬取函數
async function fetch(url) {
  try {
    const response = await axios.get(url);
    const $ = cheerio.load(response.data);
    // 在這里解析網頁內容,提取所需數據
    console.log($('selector').text());
  } catch (error) {
    console.error(`Error fetching ${url}:`, error);
  }
}

// 控制爬取速度的函數
function sleep(ms) {
  return new Promise((resolve) => setTimeout(resolve, ms));
}

// 主程序
async function main() {
  const urls = [
    'https://example.com/page1',
    'https://example.com/page2',
    'https://example.com/page3',
    // ...
  ];

  for (const url of urls) {
    await fetch(url);
    await sleep(1000); // 設置延遲1秒(1000毫秒)
  }
}

main();

在這個示例中,我們首先使用axios庫獲取網頁內容,然后使用cheerio庫解析網頁。在每次爬取網頁后,我們使用sleep函數設置一個1秒的延遲。你可以根據需要調整延遲時間以控制爬蟲速度。

0
亚洲午夜精品一区二区_中文无码日韩欧免_久久香蕉精品视频_欧美主播一区二区三区美女