koa框架和简单爬虫练习

1.koa

  1. 安装koa包: npm i -S koa@latest
  2. 引入: const koa = require("koa");
  3. 实例化对象: const app = new koa;

经过实例操做,专门用于客户端请求的函数叫作中间件,使用use()注册node

use()函数中必须使用异步 async; use但是调用无数次;
其中有两个参数:
a)ctx: 上下文环境,node的请求和响应对象,其中不建议使用node原生的req和res属性,使用koa封装的requset和response属性
b)next: next(),将本次控制权交给下一个中间件。
最后一个中间件使用next()无心义,执行完控制权返回上一层,直至第一个。npm

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(),不会执行下面的中间件json

访问localhost:3000的效果图;数组

注:会有两次操做是由于图标icon也会请求一次bash

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("监听开始");
});
复制代码

效果: app

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

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为例,效果图:koa

  1. url: 整个路径

2. path: 非查询部分

3. query: 将查询部分转为JSON对象

4. querystring: 将查询部分转为字符串

5. ctx.state ,ctx.type 表示状态吗和类型


2.简单爬虫练习

安装request,cheerio模块异步

npm i -S request: 请求模块
npm i -S cheerio: 抓取页面模块(JQ核心)
复制代码

抓取网页数据案例(随机网页)async

//导入模块
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)); //将爬到的数据写入文档中
    });
复制代码
相关文章
相关标签/搜索