用 Node.js 写一个爬虫

自己设计一个网站,然后去爬取别人家页面的数据来做一个自己的网站。哈哈哈,如果自己写着玩可能没啥事,但如果用这个网站来获利,你可能就要被寄律师函了,毕竟这有点'刑'。这篇文章呢,就带大家爬取豆瓣TOP250电影的信息。豆瓣电影 Top 250 \(douban.com\)1

准备工作

  1. 通过指令npm init初始化文件夹,会获得package.json项目说明书。

  2. 爬虫必备工具:cheerio;通过在终端输入npm i cheerio,即可将文件装到项目里。cheeriojquery 核心功能的一个快速灵活而又简洁的实现,主要是为了用在服务器端需要对 DOM 进行操作的地方。大家可以简单的理解为用来解析 html 非常方便的工具。

开始(细分七步)

  1. 用https模块(node直接提供给我们的)获取网站地址,通过get方法读取网站地址上的数据。

    const https = require('https')
    https.get('https://movie.douban.com/top250', function (res) {
    let html = ''
    res.on('data', function (chunk) {
    //console.log(chunk + '');
    //得到数据流,通过字符串拼接得到html结构
    html += chunk
    })

这样会读取到整个页面的html结构。

  1. 通过 res.on('end', function () {}),保证读取完了才会去做操作。

  2. 引入cheerio

const cheerio = require('cheerio')

  1. 获取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')
    })

这里需要注意的是我们可以去页面上看我们需要拿到哪个类名里面的内容,通过$符号可以拿到内容。

  1. 创建一个空数组,把数据以对象的形式存放在数组中

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

我们可以通过console.log(allFiles)来检查是否打印出来了我们需要的结果。

  1. 将数据写入文件,引用node官方提供的模块fs

const fs = require('fs')

  1. 创建文件夹files.json,向其中写入数据

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

到这之后,我们可以看到在当前文件夹下自动创建了文件files.json,里面已经有了我们想要的数据。

完整代码

复制代码
//引入模块
const https = require('https')
const cheerio = require('cheerio')
const fs = require('fs')
//获取页面的html结构
https.get('https://movie.douban.com/top250', function (res) {
 let html = ''
 res.on('data', function (chunk) {
 //console.log(chunk + '');
 html += chunk
 })
 res.on('end', function () {
 // 获取html中的数据
 const $ = cheerio.load(html)
 let allFiles = []
 //拿到每一个item中我们需要的数据
 $('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
 })
 })
 //console.log(allFiles);
 //将数据写入文件中
 fs.writeFile('./files.json', JSON.stringify(allFiles), function (err, data) {
 if (err) {
 throw err
 }
 console.log('文件保存成功');
 })
 })
})
相关推荐
亿牛云爬虫专家7 小时前
如何设计一套高可用的爬虫任务队列,保证断点续爬与故障转移?
redis·爬虫·故障转移·任务队列·代理ip·requests·隧道代理
二十雨辰19 小时前
[爬虫]-Urllib
爬虫·python
深蓝电商API1 天前
gRPC 数据抓取原理详解
爬虫
上海云盾-小余1 天前
全链路多层防护体系,一站式拦截 DDoS、CC、爬虫与注入攻击
网络·爬虫·安全·ddos
深蓝电商API2 天前
WebSocket 数据抓取原理与实践
爬虫
TlSfoward3 天前
抓包代理链路下的 TLS 指纹变化分析 TLSFOWARD抓包工具
数据库·爬虫·网络协议·搜索引擎·php
电商API_180079052473 天前
企业ERP进销存场景|京东商品详情接口自动同步方案|凭证鉴权批量调用技术实操
大数据·运维·人工智能·爬虫·数据挖掘·网络爬虫
拓海SEO外贸3 天前
Google 爬虫管理:抓取预算、404 与重定向
爬虫·搜索引擎·信息可视化·seo·跨境电商·独立站搭建·seo优化
深蓝电商API3 天前
浏览器缓存机制对爬虫有什么影响?
爬虫
Dontla3 天前
网站爬虫控制策略介绍(robots.txt、sitemap.xml、x-robots-tag、noindex、nofollow)网站索引
xml·爬虫·dubbo