一. 网络爬虫

1. 什么是网络爬虫

网络爬虫又被称为网页蜘蛛或网络机器人,是一种按照一定规则,自动地抓取万维网信息的程序或者脚本

2. 爬虫实例

通过爬虫爬取图片信息

url:[http://www.nipic.com/design/huanjing/index.html](http://www.nipic.com/design/huanjing/index.html)

开发思路

  1. 打开网页,查看内容,找图片地址(找规律)
    http://pic222.nipic.com/file/20190608/958400_151522024000_2.jpg
    http://pic222.nipic.com/pic/20190608/958400_151522024000_4.jpg
  2. 编写代码实现打开网页,获取所有的html页面
  3. 通过正则表达式提取出所有的图片地址
  4. 遍历图片地址数组,一个一个请求
  5. 将获取的图片数据保存在硬盘上

    3. 通过插件写爬虫

    1. 安装superagent模块

    发送请求的模块

    1. $ npm i -S superagent

    2. 安装cheerio模块

    这是一个传入一个字符串,转换成DOM对象的模块

    1. $ npm i -S cheerio

    使用后就能按照jQuery操作DOM对象,所有的API和jQuery一模一样

    3. 服务器,请求服务器内容
    1. const Koa = require('koa');
    2. //导入请求模块
    3. const request = require('superagent')
    4. // 导入cheerio模块
    5. const cheerio = require('cheerio')
    6. const app = new Koa;
    7. app.use(async (ctx,next) => {
    8. //发起请求
    9. //request是个异步的方法,所以需要放在Promise中
    10. const data =await new Promise(resolve=>{
    11. request
    12. .get('https://www.shiguangkey.com/course/search?key='+ ctx.path)
    13. .end((err,res)=>{
    14. //console.log(res)
    15. const data = res.text;
    16. // 将获取的字符串转成DOM对象
    17. const S = cheerio.load(data);
    18. //分析原网页结构
    19. console.log($('.course-item .item-txt').eq(1).text() );
    20. })
    21. resolve(arr)
    22. })
    23. app.body(arr);
    24. })
    25. app.listen(3000)