【nodejs】用Node.js实现简单的壁纸网站爬虫

1. 简介

在这个博客中,我们将学习如何使用Node.js编写一个简单的爬虫来从壁纸网站获取图片并将其下载到本地。我们将使用Axios和Cheerio库来处理HTTP请求和HTML解析。

2. 设置项目

首先,确保你已经安装了Node.js环境。然后,我们将创建一个新的文件夹,初始化项目并安装所需的依赖库:

bash 复制代码
Copy code
mkdir wallpaper-scraper
cd wallpaper-scraper
npm init -y
npm install axios cheerio
  1. 编写爬虫代码

在项目文件夹中,创建一个名为scraper.js的文件,并将你提供的代码复制粘贴进去。

javascript 复制代码
const axios = require('axios');
const cheerio = require('cheerio');
const fs = require('fs');

const baseUrl = 'http://www.netbian.com/';
const page = 3;

const pachong = async () => {
  const imgList = [];
  for (let i = 0; i < page; i++) {
    const res = await axios.get(
      `${baseUrl}index${i === 0 ? '' : `_${i + 1}`}.htm`,
    );
    const $ = cheerio.load(res.data);
    const imgList2 = $('.list li a img')
      .toArray()
      .map((item) => {
        return $(item).attr('src');
      });
    imgList.push(...imgList2);
  }
  writeFile(imgList);
};

const writeFile = async (urls) => {
  urls.forEach(async (item) => {
    try {
      const res = await axios.get(item, { responseType: 'arraybuffer' });
      const imgBuffer = Buffer.from(res.data, 'binary');
      await fs.promises.writeFile(
        `./img/${new Date().getTime()}.jpg`,
        imgBuffer,
      );
      console.log('写入成功 --- ' + item);
    } catch (error) {
      console.log('写入失败 --- ' + error);
    }
  });
};

pachong();

4. 运行爬虫

现在,你可以在命令行中运行爬虫脚本:

bash 复制代码
node scraper.js

脚本会自动爬取壁纸网站的图片并将它们下载到一个名为img的文件夹中。每张图片将使用当前时间戳作为文件名,以确保唯一性。

5. 注意事项

确保遵守网站的使用条款和条件。不要过度请求或滥用网站,以免造成不必要的麻烦。

代码中使用的选择器、URL结构等可能会因网站结构的更改而失效。需要根据实际情况进行调整。

相关推荐
搬砖的小码农_Sky6 小时前
AI Agent:Windows上Node.js安装后 npm -v报错
前端·npm·node.js·人机交互
深蓝电商API14 小时前
Puppeteer vs Playwright:多维度压测后的选型建议
爬虫·puppeteer·playwright
压码路15 小时前
BOSS直聘网页端研究【2026年9月】
爬虫·语言模型·boss直聘
深蓝电商API17 小时前
用 CDP 协议直连浏览器:绕过框架做更底层的控制
爬虫·cdp
深蓝电商API1 天前
从元素定位到等待策略:写出稳定不出错的自动化脚本
爬虫
liangshanbo12151 天前
面试题:如何优化 Webpack 的打包速度?
前端·webpack·node.js
禹凕1 天前
机器学习之Selenium(Machina Learning about Selenium)
爬虫·python·selenium·测试工具·机器学习
梅雅达编程笔记1 天前
02_BeautifulSoup网页数据提取
开发语言·爬虫·python·beautifulsoup·数据采集
2601_962177302 天前
Windows 安装 Codex CLI 入门级教程
人工智能·windows·node.js·ai编程
零域码客2 天前
零基础Python爬虫入门:从HTTP协议到 requests + BeautifulSoup 实战
爬虫·python·http