17370845950

Postman HTML响应解析指南:利用Cheerio实现高效数据提取

postman测试脚本环境中解析html响应时,常见的`document`对象或`json.parse`方法均不适用。本文将详细介绍如何在postman中利用轻量级jquery api `cheerio`库,高效、准确地解析html内容,从而提取所需数据。通过具体示例,您将掌握在postman中处理html响应的专业技巧。

引言:Postman中HTML解析的挑战

在Postman的测试脚本(Pre-request Script或Tests)环境中,我们经常需要对API响应进行处理和验证。当API返回的响应是HTML格式而非JSON时,传统的解析方法会遇到障碍。

  1. document对象不可用: 许多前端开发人员习惯使用浏览器提供的document对象(如document.getElementsByClassName)来操作DOM。然而,Postman的脚本运行在一个Node.js-like的沙箱环境中,不具备完整的浏览器DOM环境,因此document对象是未定义的,直接调用会导致运行时错误。
  2. JSON.parse不适用: 当响应内容是HTML时,尝试使用JSON.parse(response)会因为内容格式不匹配而抛出解析错误,因为HTML并非有效的JSON结构。

面对这些挑战,我们需要一种专门为服务器端HTML解析设计的工具,它既能提供类似前端DOM操作的便利性,又能在Postman的沙箱环境中稳定运行。

Cheerio:Postman HTML解析的利器

cheerio是一个快速、灵活且精简的jQuery核心功能实现,专为服务器端解析HTML和XML而设计。它能够将HTML字符串加载到一个内存中的DOM结构,然后允许您使用熟悉的jQuery选择器语法来遍历、操作和提取数据。

cheerio的优势在于:

  • jQuery-like API: 学习曲线平缓,熟悉jQuery的开发者可以迅速上手。
  • 轻量高效: 专为服务器端优化,解析速度快,内存占用低。
  • Postman内置支持: cheerio库在Postman的沙箱环境中是默认可用的,无需额外安装或导入。

在Postman中使用Cheerio解析HTML

使用cheerio在Postman中解析HTML响应的核心步骤包括加载HTML内容和使用选择器提取数据。

1. 加载HTML内容

首先,您需要从Postman的响应对象中获取原始的HTML文本,然后将其加载到cheerio实例中。

// 获取Postman响应的文本内容
const htmlResponseText = pm.response.text();

// 使用cheerio加载HTML文本,并获取一个类似jQuery的实例
const $ = cheerio.load(htmlResponseText);

在这里,pm.response.text()方法用于获取完整的响应体作为字符串。cheerio.load()函数则负责解析这个HTML字符串,并返回一个$对象,这个对象就拥有了与jQuery相似的所有选择和操作方法。

2. 选择器与数据提取

一旦HTML被加载,您就可以使用$对象以及标准的CSS选择器来查找元素并提取所需信息。

示例:提取页面标题

// 提取页面的标签文本
const pageTitle = $("title").text();
console.log("页面标题:", pageTitle); // 在Postman控制台输出
pm.environment.set("extracted_page_title", pageTitle); // 将标题存入环境变量</pre><p><strong>示例:提取特定类名元素的文本</strong></p>
<p>假设您想提取一个类名为mw-search-result-heading的元素内部的链接文本:</p><pre class="brush:php;toolbar:false;">// 提取特定类名元素的文本
const resultHeadingText = $(".mw-search-result-heading a").text();
if (resultHeadingText) {
    console.log("搜索结果标题:", resultHeadingText);
    pm.environment.set("extracted_search_heading", resultHeadingText);
} else {
    console.log("未找到类名为'mw-search-result-heading'的元素。");
}</pre><p><strong>示例:提取所有链接的href属性</strong></p><pre class="brush:php;toolbar:false;">const allLinks = [];
// 遍历所有标签
$("a").each((index, element) => {
    // 获取当前元素的href属性
    const href = $(element).attr('href');
    if (href) {
        allLinks.push(href);
    }
});
console.log("所有链接:", allLinks);
pm.environment.set("extracted_all_links", JSON.stringify(allLinks));</pre><h4>完整示例代码</h4>
<p>以下是一个更完整的Postman测试脚本示例,演示了如何结合断言和错误处理来解析HTML响应:</p><pre class="brush:php;toolbar:false;">// 1. 确保响应状态码为2xx
pm.test("响应状态码为200 OK", function () {
    pm.response.to.have.status(200);
});

// 2. 检查响应是否为HTML类型
pm.test("响应内容类型为HTML", function () {
    pm.expect(pm.response.headers.get('Content-Type')).to.include('text/html');
});

// 3. 使用Cheerio解析HTML
try {
    const $ = cheerio.load(pm.response.text());

    // 提取并验证页面标题
    const pageTitle = $("title").text();
    console.log("提取到的页面标题:", pageTitle);
    pm.environment.set("extracted_page_title", pageTitle); // 存储到环境变量
    pm.test("页面标题不为空", function () {
        pm.expect(pageTitle).to.not.be.empty;
    });

    // 提取特定CSS选择器下的文本内容
    // 假设目标HTML中有一个ID为'main-content'的div,里面有一个h1标签
    const mainHeading = $("#main-content h1").text();
    if (mainHeading) {
        console.log("主要内容标题:", mainHeading);
        pm.environment.set("extracted_main_heading", mainHeading);
        pm.test("主要内容标题包含特定文本", function () {
            pm.expect(mainHeading).to.include("欢迎"); // 假设标题包含“欢迎”
        });
    } else {
        console.log("未找到ID为'main-content'下的h1元素。");
    }

    // 提取所有图片(img标签)的src属性
    const imageUrls = [];
    $("img").each((index, element) => {
        const src = $(element).attr('src');
        if (src) {
            imageUrls.push(src);
        }
    });
    console.log("所有图片URL:", imageUrls);
    pm.environment.set("extracted_image_urls", JSON.stringify(imageUrls));
    pm.test("页面中存在图片", function () {
        pm.expect(imageUrls).to.not.be.empty;
    });

} catch (e) {
    // 捕获解析过程中的任何错误
    pm.test("HTML解析失败", function () {
        pm.expect.fail(`解析HTML时发生错误: ${e.message}`);
    });
}</pre><h3>注意事项</h3>
<ul>
<li>
<strong>环境限制</strong>: 尽管cheerio提供了类似jQuery的API,但它在Postman的沙箱环境中运行,是一个服务器端的DOM模拟。这意味着它不具备浏览器中document对象的完整功能,例如无法执行JavaScript、处理事件或进行页面渲染。它主要用于静态HTML内容的解析和数据提取。</li>
<li>
<strong>错误处理</strong>: HTML结构可能因各种原因(如页面改版、网络错误)而发生变化。在您的脚本中,务必加入健壮的错误处理机制,例如使用try-catch块来捕获cheerio.load()或选择器操作可能引发的错误,并对选择器返回空结果的情况进行判断,避免脚本中断。</li>
<li>
<strong>响应类型验证</strong>: 在尝试解析之前,最好通过检查响应头中的Content-Type来确认响应确实是HTML。这可以防止对非HTML内容(如纯文本、二进制文件)进行不必要的cheerio解析。</li>
<li>
<strong>性能考量</strong>: 对于非常庞大或复杂的HTML响应,cheerio的解析过程可能会消耗一定的CPU和内存资源。在设计测试时,请考虑响应的大小和解析的频率。</li>
</ul>
<h3>总结</h3>
<p>cheerio为Postman中的HTML响应解析提供了一个强大而熟悉的解决方案。通过利用其jQuery-like的API,您可以轻松地从HTML内容中提取所需的数据,从而实现更灵活、更全面的API测试和断言。掌握cheerio的使用,将极大地扩展您在Postman中处理各种API响应的能力,特别是当面对那些返回HTML而不是结构化数据的传统Web页面API时。将其集成到您的测试流程中,将使<img src="//public-space.oss-cn-hongkong.aliyucs.com/keji/670.jpg" />您的Postman测试脚本更加专业和健壮。</p> 
	<!-- 详情页标签输出开始  -->
<div class="xqbq" style="display:none;height:0;overflow: hidden;font-size: 0;">
<p><br>
# <a href="/tags/1541.html"  target="_blank" >html</a> 
# <a href="/tags/1542.html"  target="_blank" >js</a> 
# <a href="/tags/1543.html"  target="_blank" >前端</a> 
# <a href="/tags/1544.html"  target="_blank" >json</a> 
# <a href="/tags/4121.html"  target="_blank" >javascript</a> 
# <a href="/tags/4122.html"  target="_blank" >java</a> 
# <a href="/tags/4124.html"  target="_blank" >浏览器</a> 
# <a href="/tags/4272.html"  target="_blank" >node</a> 
# <a href="/tags/6872.html"  target="_blank" >node.js</a> 
# <a href="/tags/7324.html"  target="_blank" >css</a> 
# <a href="/tags/9834.html"  target="_blank" >jquery</a> 
 
</p>
</div>
<!-- 详情页标签输出结束  -->

<!-- 相关栏目开始 -->
<div class="xglm" style="display:none;height:0;overflow: hidden;font-size: 0;">
<p><br>相关栏目:
    【<a href='/hangye/' class=''>
        行业资讯    </a>】
    【<a href='/net/' class=''>
        网络运营    </a>】
    【<a href='/ai/' class=''>
        GEO优化    </a>】
    【<a href='/yingxiaotuiguang/' class=''>
        营销推广    </a>】
    【<a href='/seo/' class=''>
        SEO优化    </a>】
    【<a href='/jishujiaocheng/' class='on'>
        技术教程    </a>】
    【<a href='/daimazhishi/' class=''>
        代码知识    </a>】
    【<a href='/aituiguang/' class=''>
        AI推广    </a>】
</p>
</div>
<!-- 相关栏目结束 -->
<!-- 随机文章输出开始 -->
<div class="sjwz" style="display:none;height:0;overflow: hidden;font-size: 0;">
<p><br>相关推荐:
<a href='/news/7300.html'>Windows驱动无法加载错误解决方法_驱动签名验证失败处理步骤</a> 
<a href='/news/5198.html'>Win11色盲模式怎么开_Win11屏幕颜色滤镜设置【关怀】</a> 
<a href='/news/8957.html'>php嵌入式日志记录怎么实现_php将硬件数据写入本地日志文件【指南】</a> 
<a href='/news/4614.html'>C++如何将C风格字符串(char*)转换为std::string?(代码示例)</a> 
<a href='/news/5194.html'>Win11如何设置ipv6 Win11开启IPv6网络协议教程【步骤】</a> 
<a href='/news/7938.html'>Win10怎样安装Word样式库_Win10安装Word样式教程【步骤】</a> 
<a href='/news/8698.html'>Win11怎么设置鼠标宏_Win11鼠标按键自定义编程教程【详解】</a> 
<a href='/news/5111.html'>如何关闭Win10自动更新更新_Win10系统自动更新双重关闭技巧</a> 
<a href='/news/7637.html'>Mac自带的词典App怎么用_Mac添加和使用多语言词典【技巧】</a> 
<a href='/news/7405.html'>Windows10如何更改鼠标图标_Win10鼠标属性指针浏览</a> 
<a href='/news/8382.html'>如何解决Windows字体显示模糊的问题?(ClearType设置)</a> 
<a href='/news/4874.html'>C++如何使用std::optional?(处理可选值)</a> 
<a href='/news/8161.html'>如何使用正则表达式批量替换重复的 *- 模式为固定字符串</a> 
<a href='/news/6273.html'>LINUX下如何配置VLAN虚拟局域网_在LINUX交换机与服务器上的实现</a> 
<a href='/news/5578.html'>Win11怎么用设置清理回收站_Win11设置清理回收站技巧【步骤】</a> 
<a href='/news/5056.html'>Windows10系统怎么查看显卡型号_Win10 dxdiag显示选项卡</a> 
<a href='/news/8690.html'>Windows7怎么找回经典开始菜单_Windows7经典菜单找回步骤【方法】</a> 
<a href='/news/5134.html'>php中常量能用::访问吗_类常量与作用域操作符使用场景【汇总】</a> 
<a href='/news/5793.html'>Win11如何卸载OneDrive_Win11卸载OneDrive方法【教程】</a> 
<a href='/news/7702.html'>Windows怎样关闭开始菜单广告_Windows关闭开始菜单广告设置【步骤】</a> 
<a href='/news/4798.html'>Win11怎么设置默认终端应用_Windows11开发者选项终端</a> 
<a href='/news/7661.html'>如何使用Golang log记录不同级别日志_Golang log Println与Fatal示例</a> 
<a href='/news/5266.html'>php高频调试功能有哪些_php常用调试函数与工具汇总【解答】</a> 
<a href='/news/5413.html'>Win11怎么设置按流量计费_Win11限制后台流量消耗【网络】</a> 
<a href='/news/9363.html'>Win11如何查看开机时间 Win11查询系统运行时间【命令】</a> 
<a href='/news/6244.html'>Win11怎么关闭用户账户控制UAC_Windows11更改通知设置等级</a> 
<a href='/news/7004.html'>php485函数执行慢怎么优化_php485性能提升小技巧【技巧】</a> 
<a href='/news/9095.html'>Win11如何设置系统语言_Win11系统语言切换教程【攻略】</a> 
<a href='/news/4688.html'>Win11怎样激活系统密钥_Win11系统密钥激活步骤【攻略】</a> 
<a href='/news/7866.html'>如何在Golang中写入XML文件_生成符合规范的XML数据</a> 
<a href='/news/4571.html'>如何处理“XML格式不正确”错误 常见XML well-formed问题解决方法</a> 
<a href='/news/7332.html'>Win11关机界面怎么改_Win11自定义关机画面设置【工具】</a> 
<a href='/news/5792.html'>php在Linux怎么部署_LNMP环境搭建PHP服务的详细指南【指南】</a> 
<a href='/news/6226.html'>MAC怎么一键隐藏桌面所有图标_MAC极简模式切换与终端指令【方法】</a> 
<a href='/news/8094.html'>如何使用正则表达式批量替换重复的星号-短横模式为固定字符串</a> 
<a href='/news/9258.html'>Win10如何更改用户账户控制_Windows10安全中心调节UAC等级</a> 
<a href='/news/8674.html'>Python与Docker容器化部署实战_镜像构建与CI/CD流程</a> 
<a href='/news/6662.html'>windows系统如何安装cab更新补丁_windows手动安装更新包教程</a> 
<a href='/news/6119.html'>Windows如何使用BitLocker To Go加密U盘?(移动驱动器加密)</a> 
<a href='/news/7340.html'>Win11应用商店下载慢怎么办 Win11更改DNS提速下载【修复】</a> 
<a href='/news/6535.html'>Python生成器表达式内存优化_惰性计算说明【指导】</a> 
<a href='/news/5858.html'>php转mp4怎么保留字幕_php处理带字幕视频转换说明【说明】</a> 
<a href='/news/7291.html'>如何使用Golang实现微服务事件驱动_使用消息总线解耦服务</a> 
<a href='/news/6775.html'>Win11怎么更改任务栏位置_修改注册表将Win11任务栏置顶【教程】</a> 
<a href='/news/6558.html'>使用类变量定义字符串常量时如何实现类型安全的 Literal 注解</a> 
<a href='/news/9112.html'>Windows蓝屏错误0x0000001E怎么修复_KMODEEXCEPTIONNOTHANDLED排查</a> 
<a href='/news/9478.html'>Win11任务栏日历打不开怎么办 Win11修复日历通知中心【指南】</a> 
<a href='/news/4783.html'>Python多线程使用规范_线程安全解析【教程】</a> 
<a href='/news/8509.html'>c++中的std::conjunction和std::disjunction是什么_c++模板元编程逻辑运算【C++17】</a> 
<a href='/news/4718.html'>Win11蓝牙开关不见了怎么办_Win11蓝牙驱动丢失修复教程【方法】</a> 
</p>
</div>
<!-- 随机文章输出结束 -->
            </div>
            <div class="model-dectil-bottom">
              <ul class="model-dectil-chose">
                                <li><a href="/news/379434.html" title="手机如何编程html5_手机HTML5编程工具与移动端开发技巧【指南】"> 上一篇 : 手机如何编程html5_手机HTML5编程工具与移动端开发技巧【指南】</a></li>
                                <li><a href="/news/379436.html" title="html写好后怎么运行_写好html运行方法【教程】"> 下一篇 : html写好后怎么运行_写好html运行方法【教程】</a></li>
                              </ul>
              <div class="model-dectil-share hidden-xs">
                <div class="bdsharebuttonbox"><a href="#" class="bds_more" data-cmd="more"></a><a href="#" class="bds_qzone" data-cmd="qzone" title="分享到QQ空间"></a><a href="#" class="bds_tsina" data-cmd="tsina" title="分享到新浪微博"></a><a href="#" class="bds_tqq" data-cmd="tqq" title="分享到腾讯微博"></a><a href="#" class="bds_renren" data-cmd="renren" title="分享到人人网"></a><a href="#" class="bds_weixin" data-cmd="weixin" title="分享到微信"></a></div>
				<script>window._bd_share_config={"common":{"bdSnsKey":{},"bdText":"","bdMini":"2","bdPic":"","bdStyle":"0","bdSize":"16"},"share":{}};with(document)0[(getElementsByTagName('head')[0]||body).appendChild(createElement('script')).src='http://bdimg.share.baidu.com/static/api/js/share.js?v=89860593.js?cdnversion='+~(-new Date()/36e5)];</script>
              </div>
            </div>
          </div>
        </div>
      </div>
      <div class="footer hidden-xs">
  <div class="container">
    <ul class="footNav animated slideInUp wow">
            <li>
        <h3> <a href="/about/">关于我们 </a></h3>
         </li>
            <li>
        <h3> <a href="/service/">服务项目</a></h3>
         <a href="/pinpaisheji/">品牌设计</a>  <a href="/xuanchuanhuabao/">宣传画报 </a>  <a href="/wangzhanjianshe/">网站建设</a>  </li>
            <li>
        <h3> <a href="/ads/">广告推广</a></h3>
         </li>
            <li>
        <h3> <a href="/case/">案例欣赏</a></h3>
         <a href="/shejianli/">设计案例</a>  <a href="/wangzhananli/">网站案例</a>  </li>
          </ul>
    <dl class="footNa rt tc animated slideInUp wow">
      <dt><img src="/uploads/allimg/20250223/1-250223150F4502.jpg" alt=""></dt>
      <dd> 微信扫一扫<br>
        即刻关注我们公众号 </dd>
    </dl>
  </div>
  <div class="container">
    <ul class="link tc animated slideInUp wow">
          </ul>
  </div>
</div>
<div class="copy tc hidden-xs">
  <div class="container"> © <script>document.write( new Date().getFullYear() );</script> 南昌市广照天下广告策划有限公司 版权所有 <a href="https://beian.miit.gov.cn/" rel="nofollow" target="_blank">赣ICP备2024031479号</a><div style="display:none">
<a href="http://edingchen.com">广照天下广告</a>
<a href="http://www.edingchen.com">广照天下广告</a>
<a href="http://cdgjp.com">广照天下广告策划</a>
<a href="http://www.cdgjp.com">广照天下广告策划</a>
<a href="http://jobeople.com">广照天下</a>
<a href="http://www.jobeople.com">广照天下</a>
<a href="http://gztxch.cn">广照天下</a>
<a href="http://www.gztxch.cn">广照天下</a>
<a href="http://irgt.cn">广照天下</a>
<a href="http://www.irgt.cn">广照天下</a>
<a href="http://drorgan.com">广照天下广告策划</a>
<a href="http://www.drorgan.com">广照天下广告策划</a>
<a href="http://51yingcai.com.cn">广照天下广告策划</a>
<a href="http://www.51yingcai.com.cn">广照天下广告策划</a>
<a href="http://gztx8.cn">南昌市广照天下广告策划有限公司</a>
<a href="http://www.gztx8.cn">南昌市广照天下广告策划有限公司</a>
<a href="http://gztx1.cn">南昌市广照天下广告策划有限公司</a>
<a href="http://www.gztx1.cn">南昌市广照天下广告策划有限公司</a>
</div>    <p><a href="https://beian.miit.gov.cn/" rel="nofollow" target="_blank">赣ICP备2024031479号</a></p>
    <script>$(document).ready(function() { $(".banner_item1").slick({dots:true,infinite: false,arrows:false,autoplay:true,autoplaySpeed:1500 });});</script> 
  </div>
</div>
<div class="copyM tc visible-xs"><div style="display:none">
<a href="http://edingchen.com">广照天下广告</a>
<a href="http://www.edingchen.com">广照天下广告</a>
<a href="http://cdgjp.com">广照天下广告策划</a>
<a href="http://www.cdgjp.com">广照天下广告策划</a>
<a href="http://jobeople.com">广照天下</a>
<a href="http://www.jobeople.com">广照天下</a>
<a href="http://gztxch.cn">广照天下</a>
<a href="http://www.gztxch.cn">广照天下</a>
<a href="http://irgt.cn">广照天下</a>
<a href="http://www.irgt.cn">广照天下</a>
<a href="http://drorgan.com">广照天下广告策划</a>
<a href="http://www.drorgan.com">广照天下广告策划</a>
<a href="http://51yingcai.com.cn">广照天下广告策划</a>
<a href="http://www.51yingcai.com.cn">广照天下广告策划</a>
<a href="http://gztx8.cn">南昌市广照天下广告策划有限公司</a>
<a href="http://www.gztx8.cn">南昌市广照天下广告策划有限公司</a>
<a href="http://gztx1.cn">南昌市广照天下广告策划有限公司</a>
<a href="http://www.gztx1.cn">南昌市广照天下广告策划有限公司</a>
</div>  <p><a href="https://beian.miit.gov.cn/" rel="nofollow" target="_blank">赣ICP备2024031479号</a></p>
</div>

<!-- 友情链接外链开始 -->
<div class="yqljwl" style="display:none;height:0;overflow: hidden;font-size: 0;">友情链接:
<br>
</div>
<!-- 友情链接外链结束 -->
<!-- 通用统计代码 -->
<div class="tytjdm" style="display:none;height:0;overflow: hidden;font-size: 0;">
<script charset="UTF-8" id="LA_COLLECT" src="//sdk.51.la/js-sdk-pro.min.js"></script>
<script>LA.init({id:"3LOts1Z6G9mqhKAu",ck:"3LOts1Z6G9mqhKAu"})</script>
</div>
<!-- 通用统计代码 -->

<span id="WzLinks" style="display:none"></span>
<script language="javascript" type="text/javascript" src="//cdn.wzlink.top/wzlinks.js"></script>
<!-- 应用插件标签 start --> 
  
<!-- 应用插件标签 end -->
    </div>
  </div>
</div>
</body>
</html>