1.下载并引入request
cnpm install request --save; const request = require("request");
2.基本使用
request({ url: url,//请求路径 method: "POST",//请求方式,默认为get headers: {//设置请求头 "content-type": "application/json", }, body: JSON.stringify(requestData)//post参数字符串 }, function(error, response, body) { if (!error && response.statusCode == 200) { } });
栗子:
1.抓取内容 var request = require('request'); request('https://www.baidu.com', function (error, response, body) { console.log(body)//打印百度首页html内容 }) or request({url:'https://www.baidu.com'}, function (error, response, body) { console.log(body)//打印百度首页html内容 }) 2.抓取文件 request('https://www.baidu.com/img/bd_logo1.png').pipe(fs.createWriteStream('a.png')) //抓取百度logo并保存到本地 fs.createReadStream('pic.jpg').pipe(request.put('http://veb.com/upload')) //读取流pipe上传
扩展:
cheerio //npm install cheeriovar cheerio = require('cheerio'); var $ = cheerio.load('<ul id="fruits">...</ul>');//jquery 一样的操作