博客
关于我
nodeJs爬取图片
阅读量:494 次
发布时间:2019-03-07

本文共 822 字,大约阅读时间需要 2 分钟。

新建nodeJs爬取图片的小样例

1、新建node项目

这一步已经完成,生成默认的package.json文件

2、安装所需模块

爬取图片需要以下模块

  • request 模块简化http请求
  • cheerio 提供jQueryCore功能
  • fs 操作文件操作

注意:cheerio需要单独下载

3、编写抓取图片代码

新建app.js文件

代码示例:

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

function start(url) {request(url, function(err, res, body) {if (!err && res.statusCode == 200) {findImg(body, saveImgFile);}});}

function findImg(dom, callback) {let $ = cheerio.load(dom);$('img').each((index, dom) => {let imgSrc = $(dom).attr('src');callback(imgSrc, index);});}

function saveImgFile(src, index) {let ext = src.split('.').pop();imgName = index + '.' + ext;// 创建文件路径并存储图片let filePath = './pic/' + imgName;request(src).pipe(fs.createWriteStream(filePath));}

运行命令:node app.js

注意事项:

  • 请确保网络权限
  • 确保被爬的网站允许通过请求模块抓取
  • 爬取图片请遵守robots.txt规则

图片保存到pic文件夹

转载地址:http://rajcz.baihongyu.com/

你可能感兴趣的文章
Python PyQt5:如何使用 PyQt5 显示错误消息
查看>>
Python pytest 面试题!
查看>>
Python pytz 时区函数返回一个相差 9 分钟的时区
查看>>
python rabbitmq实现简单/持久/广播/组播/topic/rpc消息异步发送可配置Django
查看>>
Python random和json模块
查看>>
Python random模块seed理解
查看>>
python range()函数
查看>>
Python rdflib可传递查询
查看>>
python redis 集群_python 搭建redis集群
查看>>
python redis连接,在Python中使用Redis连接池的正确方法
查看>>
python regex_Python RegEx
查看>>
python requests post 中文结果请求得到unicode
查看>>
Python Requests接口自动化测试实战
查看>>
Python requests模块
查看>>
python request与grequests该如何选择
查看>>
python request模块
查看>>
Python requirements.txt的使用方法
查看>>
Python REST(Web 服务)框架的推荐?
查看>>
Python rsa 加密
查看>>
Python RSA操作
查看>>