<node.js學習筆記(5)>koa框架和簡單爬蟲練習

liangsheng0111發表於2018-12-12

1.koa

  1. 安裝koa包: npm i -S koa@latest
  2. 引入: const koa = require("koa");
  3. 例項化物件: const app = new koa;

通過例項操作,專門用於客戶端請求的函式叫做中介軟體,使用use()註冊

use()函式中必須使用非同步 async; use可是呼叫無數次;
其中有兩個引數:
a)ctx: 上下文環境,node的請求和響應物件,其中不建議使用node原生的req和res屬性,使用koa封裝的requset和response屬性
b)next: next(),將本次控制權交給下一個中介軟體。
最後一箇中介軟體使用next()無意義,執行完控制權返回上一層,直至第一個。

1. next引數的使用demo
const Koa = require("koa");
const koa = new Koa();
//中介軟體1
koa.use(async (ctx, next) => {
console.log("1 , 接收請求控制權");
await next();   //將控制權傳給下一個中介軟體
console.log("1 , 返回請求控制權");
});             //將中介軟體註冊到koa的例項上

//中介軟體2
koa.use(async (ctx, next) => {
 console.log("2 , 接收請求控制權");
await next();
console.log("2 , 返回請求控制權");
}); 

//中介軟體3
koa.use(async (ctx, next) => {
console.log("3 , 接收請求控制權");
 console.log("3 ,返回請求控制權");
});
koa.listen(3000, ()=>{
    console.log("開始監聽3000埠");
});
複製程式碼

注:當中介軟體中沒有next(),不會執行下面的中介軟體

訪問localhost:3000的效果圖;

<node.js學習筆記(5)>koa框架和簡單爬蟲練習

注:會有兩次操作是因為圖示icon也會請求一次

2.ctx引數的使用demo
const Koa = require("koa");
const koa = new Koa(); 
koa.use(async (ctx, next)=>{
    ctx.body = "body可以返回資料,";
    ctx.body += "可以多次呼叫,";
    ctx.body += "不需要end()";
});
koa.listen(3000, ()=>{
    console.log("監聽開始");
});
複製程式碼

效果:

<node.js學習筆記(5)>koa框架和簡單爬蟲練習

ctx.url ,ctx.path ,ctx.query ,ctx.querystring ,ctx.state ,ctx.type

const Koa = require("koa");
const koa = new Koa(); 
koa.use(async (ctx, next)=>{
    ctx.body = ctx.url;
    ctx.body = ctx.path;
    ctx.body = ctx.query;
    ctx.body = ctx.querystring;
});
koa.listen(3000, ()=>{
    console.log("監聽開始");
});
複製程式碼

訪問http://localhost:3000/path?name=sjl&age=18為例,效果圖:

  1. url: 整個路徑

<node.js學習筆記(5)>koa框架和簡單爬蟲練習
2. path: 非查詢部分

<node.js學習筆記(5)>koa框架和簡單爬蟲練習
3. query: 將查詢部分轉為JSON物件

<node.js學習筆記(5)>koa框架和簡單爬蟲練習
4. querystring: 將查詢部分轉為字串

<node.js學習筆記(5)>koa框架和簡單爬蟲練習
5. ctx.state ,ctx.type 表示狀態嗎和型別


2.簡單爬蟲練習

安裝request,cheerio模組

npm i -S request: 請求模組
npm i -S cheerio: 抓取頁面模組(JQ核心)
複製程式碼

抓取網頁資料案例(隨機網頁)

//匯入模組
const request = require("superagent"); //匯入請求模組
const cheerio = require("cheerio");
const {join} = require("path");
const fs = require("fs");

let arr = [],   //存放資料
    reg = /\n|\s+/g,  //replace中使用
    url = "";
request
    .get(url)
    .end((err, res) => {
        const $ = cheerio.load(res.text); //把字串內的標籤當成dom來使用
        $(".course-item").each((i, v) => {
            // v當前進來的dom,根據網頁的佈局結構來找到準確的dom節點
            const obj = {
                imgSrc : $(v).find("img").prop("src"),
                price :  $(v).find(".fr span").text().replace(reg, ""),
                total :  $(v).find(".item-txt").text().replace(reg, ""),
                href : join(url + $(v).find(".cimg").prop("href"))
            };
            console.log(join(url + $(v).find(".cimg").prop("href"))); //拼接
            arr.push(obj); //把物件放進陣列裡
        });
        
        fs.writeFile("./sjl.json", JSON.stringify(arr)); //將爬到的資料寫入文件中
    });
複製程式碼

相關文章