【问题标题】:Extract a value from a HTML response with Cheerio using Postman使用 Postman 从带有 Cheerio 的 HTML 响应中提取值
【发布时间】:2021-08-12 19:36:23
【问题描述】:

我正在尝试使用 Postman 从请求中获取一个返回 HTML 响应的值。我在脚本部分使用 Cheerio。

响应如下所示:

    <table class="etlsessions-table" cellpadding="0" cellspacing="0">
        <thead>
            <tr>
                <th class="someclass1">
                    <div>
                        <span>info1</span>
                    </div>
                </th>
                <th class="someclass2">
                    <div>
                        <span>info2</span>
                    </div>
                </th>
                <th class="someclass3">
                    <div>
                        <span>info3</span>
                    </div>
                </th>
                <th class="someclass2">
                    <div>
                        <span>info4</span>
                    </div>
                </th>
            </tr>
        </thead>
        <tbody>
            <tr class="someclass5">
                <td class="someclass">
                    <nobr>info5</nobr>
                </td>
                <td class="someclass6">
                    <nobr>info6</nobr>
                </td>
                <td class="someclass3">info7</td>
                <td class="someclass7">
                    <a href="http://www.google.com">someurl1</a>
                </td>
            </tr>
       </tbody>
    </table>

如何从someclass6 类中获取info6 值?

【问题讨论】:

    标签: html postman cheerio


    【解决方案1】:

    由于 Cheerio 是 Postman 沙箱环境内置的,您可以使用它来获取元素的值。

    我不确定您的完整用例,但您可以将类似这样的基本内容添加到 Tests 脚本并将值打印到控制台:

    const $ = cheerio.load(pm.response.text()),
        elementValue = $('.someclass6 nobr').text();
    
    console.log(elementValue)
    

    【讨论】:

      【解决方案2】:

      Postman 是一款允许您调用 API 端点的软件,因此基本上您的程序将使用 node.js 编写,您将使用 postman 调用端点。

      在这种情况下并使用cheerio,代码将如下所示:

      function getResponse() {
      
      return fetch(`${YOUR API END POINT URL}`)
      .then(response => response.text())
      .then(body => {
        const $ = cheerio.load(body);
        const $info6= $('.someclass6 td );
      
        const info6= $info6.first().contents().filter(function() {
          return this.type === 'text';
        }).text().trim();
        const response= {
          info6,
        };
      
        return response;
      });
      }
      

      祝你好运!

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2023-03-31
        • 2023-03-18
        • 1970-01-01
        • 1970-01-01
        • 2015-10-11
        • 2021-03-26
        • 2021-12-14
        • 2020-09-27
        相关资源
        最近更新 更多