使用 Node.js 和 Cheerio 爬取网站图片

写一个关于图片爬取的小案例

爬取效果

使用插件如下:

{
  "dependencies": {
    "axios": "^1.6.0",
    "cheerio": "^1.0.0-rc.12",
    "request": "^2.88.2"
  }
}

新建一个config.js配置文件

// 爬取图片网站
const url = 'http://m.hydcd.com/cy/fkccy/index9.htm'//可以自行修改网址
// http://www.hydcd.com/cy/fkccy/index.htm
// http://m.hydcd.com/cy/fkccy/
const path = require('path');
//图片下载文件夹
const imgDir = path.join(__dirname, 'img')
 
module.exports.url = url
module.exports.imgDir = imgDir

找到需要下载的文件原元素位置

const cheerio = require('cheerio')

function findImg(dom, callback) {
  let $ = cheerio.load(dom,{decodeEntities: false});

  //找到图片的位置 并获取图片链接
  $('table tbody tr td  img').each(function (i, elem) {

    let imgSrc = $(this).attr('src');
    let alt = $(this).attr('alt');
    callback(imgSrc, i,alt)
  })
}
module.exports.findImg = findImg;

const request = require('request')
const path = require('path')
const config = require('./config')
const analyze = require('./analyze')
const fs = require('fs')
 
function start() {
  request(config.url, function (err, res, body) {
    console.log('start');
    if (!err && res) {
      console.log('start');

      analyze.findImg(body, download,{decodeEntities: false});
    }
  })
}
//这个图片地址链接前缀
let imgUrlPath = "http://m.hydcd.com/cy/fkccy/"
function download(imgUrl, i,alt) {
    console.log(imgUrl,"11111")
  let txt = imgUrl.split('images/')[1];
  request(imgUrlPath+imgUrl).pipe(fs.createWriteStream(path.join(config.imgDir,  txt), {
    'encoding': 'UTF-8',
  }))
}
 
start();

以下是一个使用 Node.js 和 Cheerio 爬取网站图片的示例代码:

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

// 定义要爬取的网页 URL
const url = 'https://example.com';

// 发起 GET 请求获取网页内容
axios.get(url)
  .then(response => {
    // 使用 Cheerio 加载网页内容
    const $ = cheerio.load(response.data);

    // 定义一个数组来保存图片 URL
    const imageUrls = [];

    // 遍历页面中的图片标签
    $('img').each((index, element) => {
      // 获取图片的 src 属性值
      const imageUrl = $(element).attr('src');
      // 将图片的 URL 添加到数组中
      imageUrls.push(imageUrl);
    });

    // 下载图片
    imageUrls.forEach((imageUrl, index) => {
      // 发起 GET 请求获取图片内容
      axios.get(imageUrl, { responseType: 'stream' })
        .then(response => {
          // 创建一个可写流,将图片内容写入到文件中
          const writeStream = fs.createWriteStream(`image${index+1}.jpg`);
          // 将响应的数据流导向可写流
          response.data.pipe(writeStream);
        })
        .catch(error => {
          console.error(`下载图片失败:${error}`);
        });
    });
  })
  .catch(error => {
    console.error(`获取网页内容失败:${error}`);
  });

请注意,上述示例中的 https://example.com 是一个示例网站的 URL,你需要替换为你要爬取图片的实际网站 URL。

这段代码首先使用 Axios 发起 GET 请求获取网页内容,然后使用 Cheerio 加载网页内容,对图片标签进行遍历,获取图片的 src 属性值并保存到一个数组中。最后,通过循环遍历数组中的图片 URL,使用 Axios 再次发起 GET 请求获取图片内容,并通过可写流将图片内容写入到文件中。你可以自定义文件名和保存路径。

请注意,进行网站爬取时,一定要遵守法律法规,并注意对网站的使用限制和版权保护。同时,不要对不允许爬取的网站进行爬取,以免触犯相关法律法规并造成不良后果!!!!

  • 9
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

随风小薇

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值