node爬虫,不难

53 阅读2分钟

你想过自己写个网站,把别人网站上的数据"借"过来用吗?

准备工作

首先,创建一个新文件夹,打开终端输入:

npm init

一路按回车,就会生成一个package.json文件,这是项目的"说明书"。

然后安装爬虫神器——cheerio:

npm i cheerio

cheerio可以理解为服务器端的jQuery,能帮我们轻松解析网页内容。

七步完成爬虫

第一步:引入所需模块

const https = require('https')
const cheerio = require('cheerio')
const fs = require('fs')

第二步:获取网页内容

https.get('https://movie.douban.com/top250', function (res) {
  let html = ''
  res.on('data', function (chunk) {
    html += chunk
  })

这里我们通过https模块读取豆瓣TOP250页面的整个HTML内容。

第三步:等数据加载完再处理

  res.on('end', function () {
    // 这里处理数据
  })
})

第四步:解析HTML内容

const $ = cheerio.load(html)
$('li .item').each(function () {
  const title = $('.title', this).text()
  const star = $('.info .bd .rating_num', this).text()
  const pic = $('.pic img', this).attr('src')
})

这里我们通过查看网页源代码,找到需要的类名,用$符号获取电影标题、评分和图片链接。

第五步:创建数组存储数据

let allFiles = []
allFiles.push({
  title: title,
  star: star,
  pic: pic
})

第六步:写入文件

fs.writeFile('./files.json', JSON.stringify(allFiles), function (err) {
  if (err) {
    throw err
  }
  console.log('文件保存成功')
})

用fs模块将数据保存为json文件。

第七步:运行代码

在终端输入:

node 你的文件名.js

如果一切顺利,你会看到当前文件夹下生成了files.json文件,里面就是爬取到的电影数据!

完整代码

const https = require('https')
const cheerio = require('cheerio')
const fs = require('fs')

https.get('https://movie.douban.com/top250', function (res) {
  let html = ''
  
  res.on('data', function (chunk) {
    html += chunk
  })
  
  res.on('end', function () {
    const $ = cheerio.load(html)
    let allFiles = []
    
    $('li .item').each(function () {
      const title = $('.title', this).text()
      const star = $('.info .bd .rating_num', this).text()
      const pic = $('.pic img', this).attr('src')
      
      allFiles.push({
        title: title,
        star: star,
        pic: pic
      })
    })
    
    fs.writeFile('./files.json', JSON.stringify(allFiles), function (err) {
      if (err) {
        throw err
      }
      console.log('文件保存成功')
    })
  })
})

小结

看,用Node.js写爬虫其实并不难吧!

作为前端开发者,我们应该了解Node.js的强大能力,它不仅能写后端,还能做很多有趣的事情。