使用 Nodejs 内置模块 + shell 脚本 实现简单的图片爬虫
用到的模块 https
用于请求child_process
用于执行 shell 脚本
引入内置模块 http / https
1
| const https = require('https');
|
引入 spawn 模块
1
| const { spawn } = require('child_process');
|
定义要获取图片的 url 地址
1
| const url = 'https://www.duitang.com/article/?id=870171';
|
定义正则匹配
1
| const reg = /http(s)?:\/\/([\S]*)\.(jpg|jpeg|png|gif|webp)/g;
|
发起请求
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
| https.get(url, (res) => { let str = '';
res.on('data', (data) => { str += data; });
res.on('end', () => { let i;
while ((i = reg.exec(str))) { let item = i[0];
spawn('sh', ['index.sh', item]); } console.log('执行'); }); });
|
shell 脚本编写
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
| #!/bin/sh
time=$(date "+%Y%m%d%H%M%S")-$RANDOM
type="${1##*.}"
if [ ! -d "img" ]; then mkdir img fi
curl $1 -o ./img/$time.$type
exit 0;
|
执行 index.js 脚本
执行脚本一定要在当前目录下。
如果 url 是 https 开头 那么发起请求 就需要用 https 否则 http 就可以。
正常执行后,会在当前目录下,新建 img 文件夹,里面是下载好的图片。