使用 Postman 从 Cheerio 的 HTML 响应中提取值

问题描述

我正在尝试从请求中获取一个值,该值使用 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>

如何从 info6 类中获取 someclass6 值?

解决方法

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;
});
}

祝你好运!

,

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

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

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

console.log(elementValue)