天天看點

nodejs爬蟲擷取漫威超級英雄電影海報

昨天去看了《複聯3》的首映,當我提前15分鐘進入影院的時候, 看到了粉絲們取票的長隊, 頓時有一種跨年夜的感覺...

最近看了node爬蟲的一些知識, 這裡用node爬取一下漫威官網的電影海報!

marvel
// https://marvel.com/movies/all
const request = require('superagent')
const cheerio = require('cheerio')
const fs = require('fs-extra')
const path = require('path')

let url = 'https://marvel.com/movies/all'

// 擷取圖檔url和圖檔名字
async function getUrlAndName(){
    // 用于存儲傳回值
    let imgAddrArray = []
    // 請求資源
    const res = await request.get(url)
    // 将擷取的html, 轉換為資源符$, 相當于python中的xpath文法的etree過程
    const $ = cheerio.load(res.text)
    // 定位資源位置, 将圖檔資源,和圖檔名字, 以數組方式, 傳回給調用函數
    $('.row-item-image a').each(function(i, elem){
        let movieName = $(this).attr('href').split('/').pop()
        let imgAddr = $(this).find('img').attr('src')
        imgAddrArray.push([imgAddr, movieName])
    })
    return imgAddrArray
}
// 下載下傳圖檔
async function download(imgAndName){
    // 拼接出, 目前資源的檔案名
    let filename = imgAndName[1] + '.jpg'
    console.log("爬取海報:", filename);
    // 擷取圖檔二進制資料
    const req = request.get(imgAndName[0]);
    // 儲存圖檔
    await req.pipe(fs.createWriteStream(path.join(__dirname, 'images', filename))); 
}

// 建立檔案夾, 控制整體流程
async function init(){
    let imgAddrArray = await getUrlAndName()
    // 建立檔案夾
    try{
        await fs.mkdir(path.join(__dirname, 'images'));
    }
    catch(err){
        console.log("==>", err);
    }
    // 擷取資源
    for (let imgAddr of imgAddrArray){
        await download(imgAddr);
    }
}

init()
           
運作結果

小結:

直覺感受, node爬蟲并沒有python好用, 而且由于浏覽器的同源限制, 在浏覽器端跑node爬蟲也會有些麻煩;node爬蟲的優勢:理論上講,node預設的異步玩法, 能達到python的多線程爬蟲的效果.

寫爬蟲, 還是老老實實用python吧!