用 node 寫一個爬蟲,超簡單!
前言
你是否有一個想法,自己設計一個網站,然後去爬取別人家頁面的數據來做一個自己的網站。哈哈哈,如果自己寫着玩可能沒啥事,但如果用這個網站來獲利,你可能就要被寄律師函了,畢竟這有點‘刑’。這篇文章呢,就帶大家爬取豆瓣 TOP250 電影的信息。豆瓣電影 Top 250 (douban.com)[1]
準備工作
-
通過指令
npm init
初始化文件夾,會獲得package.json
項目說明書。 -
爬蟲必備工具:
cheerio
;通過在終端輸入npm i cheerio
,即可將文件裝到項目裏。cheerio
是jquery
核心功能的一個快速靈活而又簡潔的實現,主要是爲了用在服務器端需要對DOM
進行操作的地方。大家可以簡單的理解爲用來解析html
非常方便的工具。
開始 (細分七步)
- 用 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 結構。
-
通過
res.on('end', function () {})
,保證讀取完了纔會去做操作。 -
引入
cheerio
const cheerio = require('cheerio')
- 獲取
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
})
我們可以通過console.log(allFiles)
來檢查是否打印出來了我們需要的結果。
- 將數據寫入文件,引用
node
官方提供的模塊fs
const fs = require('fs')
- 創建文件夾
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('文件保存成功');
})
})
})
結語
到這裏你會發現node
的爬蟲寫起來不是很難的,作爲一名前端新手我們應該知道node
它是非常強大的,它能讀得懂js
可以用來做後端開發。本文的實現是爬取一些簡單的數據,是一個入門,希望對未來學習node
有幫助。
參考資料
[1]
https://movie.douban.com/top250
關於本文
來源:一拾九
https://juejin.cn/post/7224873698981494821
本文由 Readfog 進行 AMP 轉碼,版權歸原作者所有。
來源:https://mp.weixin.qq.com/s/wWoVmOXYNHHZ1_e4lfTiIw