一. 网络爬虫
1. 什么是网络爬虫
网络爬虫又被称为网页蜘蛛或网络机器人,是一种按照一定规则,自动地抓取万维网信息的程序或者脚本
2. 爬虫实例
通过爬虫爬取图片信息
url:[http://www.nipic.com/design/huanjing/index.html](http://www.nipic.com/design/huanjing/index.html)
开发思路
- 打开网页,查看内容,找图片地址(找规律)
http://pic222.nipic.com/file/20190608/958400_151522024000_2.jpg
http://pic222.nipic.com/pic/20190608/958400_151522024000_4.jpg - 编写代码实现打开网页,获取所有的html页面
- 通过正则表达式提取出所有的图片地址
- 遍历图片地址数组,一个一个请求
-
3. 通过插件写爬虫
1. 安装
superagent模块发送请求的模块
$ npm i -S superagent
2. 安装
cheerio模块这是一个传入一个字符串,转换成DOM对象的模块
$ npm i -S cheerio
使用后就能按照jQuery操作DOM对象,所有的API和jQuery一模一样
3. 服务器,请求服务器内容
const Koa = require('koa');//导入请求模块const request = require('superagent')// 导入cheerio模块const cheerio = require('cheerio')const app = new Koa;app.use(async (ctx,next) => {//发起请求//request是个异步的方法,所以需要放在Promise中const data =await new Promise(resolve=>{request.get('https://www.shiguangkey.com/course/search?key='+ ctx.path).end((err,res)=>{//console.log(res)const data = res.text;// 将获取的字符串转成DOM对象const S = cheerio.load(data);//分析原网页结构console.log($('.course-item .item-txt').eq(1).text() );})resolve(arr)})app.body(arr);})app.listen(3000)
