Postman中获取HTML格式返回结果的标签值——使用jQuery核心库cheerio

什么是jQuery库

jQuery是一个快速,简洁的JavaScript库,由John Resig创建于2006年,有一个很好的座右铭:少写,多做。

jQuery 简化了 HTML 文档遍历,事件处理,动画和Ajax交互快速Web开发。

通过 jQuery,您可以选取(查询,query) HTML 元素,并对它们执行"操作"(actions)。

基础语法

  $(selector).action()
  • 美元符号定义 jQuery
  • 选择符(selector)"查询"和"查找" HTML 元素
  • jQuery 的 action() 执行对元素的操作

JQuery中text()、html()、val()的区别

  • text():返回或设置被选元素的文本内容
  • html():返回或设置被选元素的内容(inner HTML),包括标签。打印当前标签内的文本内容,如果有子标签,则把子标签本身和子标签内的文本一起打印
  • val():返回或设置被选元素的值,主要用于获取表单元素的值,如果该方法未设置参数,则返回被选元素的当前值。只针对标签的value属性。

jQuery核心库——cheerio库

选自:https://blog.csdn.net/github_37287822/article/details/84036296
这个库是特别为服务器端实现的一个快速敏捷的Jquery核心库。

  • 它的实现是基于Jquery的核心库。它从Jquery库中移除了所有DOM的冲突和令人不爽的浏览器的东西。
  • 它始终工作在一个持续的单一的DOM模型中。对于语法解析,手动操纵和渲染都是异常地迅速。以后端-后端的标准进行测试
  • cheerio包包括Parse5语法解析器并且可选性支持htmlparser2。它可以解析HTML和XML。

加载方式

cheerio核心是选取的jquery库,加载方式与jQuery一致。

  //require():运行时调用模块
  const cheerio = require('cheerio')
  const $ = cheerio.load('html doc')

选择器

  $( selector, [context], [root] )
  • selector是搜索的是根元素范围内的上下文。
  • selector和 context可以是一个字符串表达式,一个DOM元素,一个DOM元素数组,更或者是一个cheerio对象。
  • root一般情况下是一个HTML的文本字符串。

举例:

  $('.apple','#fruit').text()
  $('ul .pear').attr('class')
  $('li[class=orange]').html()

属性

  • .attr(name,value) :需要注意的是改变的是匹配到的第一个元素的值
  $('ul').attr('id') ##get method
  $('.apple').attr('id','favorite').html() ## set the element which class is apple
  • .prop(name,value)
  $('input[type="checkbox"]').prop('checked') ## return the first patched element boolean
  $('input[type="checkbox"]').prop('checked',true).val() ## return ok represent the value setted succeed.
  • .data(name,value):返回或者设置匹配到第一个元素的属性
  $('<div data-apple-color="red"></div>').data()
  ## =>{ appleColor: 'red' }
  $('<div data-apple-color="red"></div>').data('appleColor')
  ## => red
  const apple = $('.apple').data('kind', 'mac')
  apple.data('kind')
  ## => mac  set the kind as mac. apple.data is stated the result after manipulate.
  • .val(name,value)
  /**
  *     返回或者设置 input select textarea的值
  */
  $('input[type="text"]').val()
  ## => get the input default val is input_text
  $('input[type="text"]').val('test').html()
  ## => set the input value is test. The result is test.
  • .removeAttr(name,value)
  /**
  *  通过名字移除属性,这个名字可以使id名或者类名
  */
  $('.pear').removeAttr('class').html() 
  ## => 显示的是移除类名为pear的类
  $('#pear').removeAttr('class').html()
  ## => 自行体会
  • .hasClass(name,value)

  • .addClass(name,value)

  • .removeClass(name,value)

  • .toggleClass(name,value)

  • .is(Selector)&& .is(element)&& .is(selection)&& .is(function(index))

Postman相关使用

测试一个接口,post数据后返回结果为HTML格式,其中一个标签中有需要获取的数据。之前在网上搜索到一个方案https://www.cnblogs.com/fxcity/p/11055463.html,但是根据其编写脚本后,console.log不出东西,显示undefined。

于是又搜索一番,发现可以直接使用cheeriohttps://www.cnblogs.com/xinxin1994/p/11258810.html,下为具体代码:

  //使用cheerio对返回的HTML操作
  var cheerio = require('cheerio');
  $ = cheerio.load(responseBody);
  //获取到标签p内的文字,并打印
  console.log($('p').text())
  //使用正则匹配开头条目数[0-9]*,记住match返回的是list格式,取出数字
  var num = ($('p').text()).match(/[0-9]*/)[0]
  console.log(typeof(num),num) //这时数字格式为str,需要强制转换为int
  var title_num = Number(num)
  console.log(typeof(title_num),title_num)

  //将条目数存为全局变量
  pm.globals.set("title_num", title_num);

使用pm.sendRequest获取HTML格式返回结果的标签值时要注意

  • 1-构造request时,记得在header中添加Content-Type

  • 2-body为表格时,使用下列格式传参:

    body:{
            mode:'urlencoded',
            urlencoded:[
                {key:"key1",value:"value1"},
                {key:"key2",value:"value2"}
            ]
        }
    
  • 3-获取html结果可使用response.text(),导入cheerio解析:

      //使用cheerio对返回的HTML操作
       var cheerio = require('cheerio');
       $ = cheerio.load(response.text())
    

具体示例代码如下:

     //构造请求
     const addRequest = {
         url:"http://hollywang.pythonanywhere.com/",
         method:"POST",
         header:{
             'Content-Type':'text/html; charset=utf-8',
         },
         body:{
             mode:'urlencoded',
             urlencoded:[
                 {key:"title",value:"test"},
                 {key:"year",value:"2020"},
                 {key:"submit",value:"Add"}
             ]
         },
     }

     //发送请求
     pm.sendRequest(addRequest, function (err, response) {
         console.log(response.code);

         //使用cheerio对返回的HTML操作
         var cheerio = require('cheerio');
         $ = cheerio.load(response.text())
         //获取到标签p内的文字,并将数字取出
         console.log($('p').text())
         //使用正则匹配开头条目数[0-9]*,记住match返回的是list格式,取出数字
         var num = ($('p').text()).match(/[0-9]*/)[0]
         console.log(typeof(num),num) //这时数字格式为str,需要强制转换为int
         var test_num = Number(num)

         //将条目数存为全局变量
         pm.globals.set("test_num", test_num);   
     });

针对HTML标签值编写Tests脚本

假设条目添加成功后,标签p中会生成title - year的数据,下为具体代码:

     var titleT = data['titleT'];
     var yearT = data['yearT'];

     pm.test("item check", function () {
         var cheerio = require('cheerio');
         $ = cheerio.load(responseBody);
         pm.expect($.text()).to.include(titleT," - ",yearT);
     });

获取表单内容

摘自:https://blog.csdn.net/gaoxilong526/article/details/82911709

可通过val() 方法返回或设置被选元素的值。元素的值是通过 value 属性设置的。该方法大多用于 input 元素。

另:返回结果HTML格式时,cheerio可用text(),html()和val()等方法获取内容:

  • text():返回或设置被选元素的文本内容,只输出标签内文本
  • html():返回或设置被选元素的内容(inner HTML),打印当前标签内的文本内容,如果有子标签,则把子标签本身和子标签内的文本一起打印
  • val():返回或设置被选元素的值,只针对标签的value属性

示例代码如下:

  <body>
      <div id="div1">div有文本内容</div>
      <div id="div2">
          div2内的文本
          <span>span内有文本内容</span>
      </div>
      <input type="text" id="input1" value="这是一个input标签">
      <input type="text" name="" id="input2" placeholder="能成功获取">
      <button id="button1" value="这是一个button标签"></button>
  </body>

在使用cheerio时,若通过id定位input标签,需要在id前加#,例如:

    console.log($("#div1").text());
    console.log($("#div2").text());
    console.log($("#div2 span").text()) ;
    console.log($("#input1").text());
    console.log($("#input2").text());
    console.log($("#button1").text());

如果input标签内部没有id值,可以将input标签下的值集合取到,再进行筛选

下面的例子要查询input标签下的Name和Year两个输入框的value值

    <form method="post">
            Name<input type="text" name="title" autocomplete="off" required value="editGet">
            Year<input type="text" name="year" autocomplete="off" required value="0000">
            <input class="btn" type="submit" name="submit" value="Update">
    </form>

获取代码如下:

    var cheerio = require("cheerio");
    var $ = cheerio.load(responseBody);
    var title = $("input[name=title]").val(); //$("input[name=title]")获取到title对象,要获取value值需使用cheerio的val()方法
    var year = $("input[name=year]").val();
    //另一种获取方法:
    var title =$("input[name=title]")[0].attribs.value); //需要明确返回对象的结构,最好用上一种方法
    var year =$("input[name=year]")[0].attribs.value);

【这里提一下iQuery中获取form内容的方法:】

摘抄自:https://blog.csdn.net/rentian1/article/details/51194207
根据name属性查找

  • $("div[id]") 选择所有含有id属性的div元素
  • $("input[name='keleyicom']") 选择所有的name属性等于'keleyicom'的input元素
  • $("input[name!='keleyicom']") 选择所有的name属性不等于'keleyicom'的input元素
  • $("input[name^='keleyi']") 选择所有的name属性以'keleyi'开头的input元素
  • ("input[name='keleyi']") 选择所有的name属性以'keleyi'结尾的input元素
  • $("input[name*='keleyi']") 选择所有的name属性包含'keleyi'的input元素
  • ("input[id][name='keleyi']") 可以使用多个属性进行联合选择,该选择器是得到所有的含有id属性并且name属性以keleyi结尾的元素

根据name取值:

  • $("input[name='mobile']").val()

**根据id取值: **

  • $("#mobile_reg_form").html()
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容