用 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('文件保存成功');
 })
 })
})
相关推荐
lbb 小魔仙21 小时前
【Python】零基础学 Python 爬虫:从原理到反爬,构建企业级爬虫系统
开发语言·爬虫·python
努力变大白1 天前
借助AI零基础快速学会Python爬取网页信息-以天眼查爬虫为例
人工智能·爬虫·python
AC赳赳老秦1 天前
Unity游戏开发实战指南:核心逻辑与场景构建详解
开发语言·spring boot·爬虫·搜索引擎·全文检索·lucene·deepseek
小花皮猪2 天前
LLM驱动智能数据采集:2026年10大AI网络爬虫工具对比评测
爬虫
我药打十个2 天前
搭建稳定的ip代理池方法
爬虫·计算机网络·ip·ip代理池
sa100272 天前
基于Python的京东评论爬虫
开发语言·爬虫·python
电商API_180079052472 天前
B站视频列表与详情数据API调用完全指南
大数据·人工智能·爬虫·数据分析
我想吃烤肉肉2 天前
wait_until=“domcontentloaded“ 解释
开发语言·前端·javascript·爬虫·python