• puppeteer 拦截页面请求


    原文链接 https://www.cnblogs.com/ajanuw/p/10324269.html

    Request

    Response

    page.setRequestInterception(true) 开启拦截

    req.respond() 返回一个自定义响应

    req.continue() 继续请求

    注意:

    • 监听的请求的类型有: document,stylesheet,image,media,font,script,texttrack,xhr,fetch,eventsource,websocket,manifest,other
    • 拦截请求需要开启 await page.setRequestInterception(true);
    • await req.respond()和await req.continue() 不能同时调用
    • 使用await req.respond() 拦截返回值注意跨域
    • 使用await req.respond() 拦截返回值注意返回json或字符串

    main.js

    const pptr = require('puppeteer');
    
    async function bootstrap() {
      const browser = await pptr.launch({
        headless: false,
        slowMo: 250,
      });
      const page = await browser.newPage();
      page.on('console', m => {
        // console.log(m.text());
      });
    
      await page.setRequestInterception(true);
      page.on('request', async req => {
        if (req.resourceType() === 'xhr') {
          console.log(req.url());
          await req.respond({
            status: 200,
            headers: {
              'Access-Control-Allow-Origin': '*',
            },
            contentType: 'application/json; charset=utf-8',
            body: JSON.stringify({ code: 0, data: 'hello puppeteer' }),
          });
          // await req.continue();
        } else {
          await req.continue();
        }
      });
    
      page.on('response', async res => {
        if (res.url().indexOf('/header') >= 0) {
          console.log(res.status());
    
          // 原本接口返回的数据 {"code":0,"data":"hello ajanuw"}
          console.log(await res.text());
          // await browser.close();
        }
      });
    
      page.on('requestfinished', req => {
        console.log(`请求完成: ${req.url()}`);
      });
    
      page.on('requestfailed', req => {
        console.log(`请求失败: ${req.url()}`);
      });
    
      await page.goto('http://127.0.0.1:5500/index.html');
    }
    
    bootstrap();
    

    index.html

    <!DOCTYPE html>
    <html lang="en">
      <head>
        <meta charset="UTF-8" />
        <meta name="viewport" content="width=device-width, initial-scale=1.0" />
        <meta http-equiv="X-UA-Compatible" content="ie=edge" />
        <title>Document</title>
      </head>
      <body>
        <div id="app">
          <button @click="get()">click get</button>
          <p>{{ data | json }}</p>
        </div>
        <script src="https://unpkg.com/vue@2.5.22/dist/vue.min.js"></script>
        <script src="https://unpkg.com/axios@0.18.0/dist/axios.min.js"></script>
        <script>
          const http = axios.create({
            baseURL: 'http://127.0.0.1:5000',
          });
          new Vue({
            el: '#app',
            data() {
              return {
                data: ''
              };
            },
    
            methods: {
              get() {
                http('/header').then(({ data }) => {
                  console.log(typeof data.data);
                  this.data = data
                });
              },
            },
    
            mounted() {},
          });
        </script>
      </body>
    </html>
    

    接口

    @Get('/header')
    @Header('Access-Control-Allow-Origin', '*')
    test() {
        return {
          code: 0,
          data: 'hello ajanuw',
        };
    }
    
  • 相关阅读:
    MySQL用户管理
    MySQL慢查询日志总结
    linux rinetd 端口转发部署
    CentOS6.8下安装MySQL5.6
    ELK filter过滤器来收集Nginx日志
    ELK+Redis 解析Nginx日志
    为什么很多IT公司不喜欢进过培训机构的人呢?
    Django之virtualenv下安装xadmin
    Django开发问题及解决方法汇总
    解决Pycharm添加虚拟解释器的报错问题
  • 原文地址:https://www.cnblogs.com/ajanuw/p/10324269.html
Copyright © 2020-2023  润新知