【问题标题】:Cheerio get content of p tag within section tagCheerio 获取部分标签内 p 标签的内容
【发布时间】:2019-02-15 17:31:27
【问题描述】:

Cheerio 不返回嵌套在多个其他标签之间的<p id="target-content"> 标签的内容。我使用cheerio和请求。我的代码看起来像这样,但它总是返回null

我尝试获取id为id=target-content的段落内容。

var webpage = '...';
request(webpage, function(err, res, body) {
if (err) console.err(err);
if (res.statusCode === 200) {
    var $ = cheerio.load(body);
    $('p[id="target-content"]').text(); // returns null
}
});


<body>
    <div id="foobar">
        <div>...</div>
        <div>...</div>
        <div>...</div>
        <section id="foo">
            <header></header>
            <section id="bar">
                <div></div>
                <div></div>
                <section id="container">
                    <p id="target-content">
                        Stackoverflow is amazing.
                    </p>
                </section>
            </<section>
        </section>
    </div>
</body>

我希望输出 Stackoverflow is amazing,但我得到 null 或者根本没有输出。我很感激任何帮助。非常感谢。

【问题讨论】:

  • 您是否检查过res.statusCode === 200 是否为真并且if 中的代码是否已执行?另外,您如何检查$('p[id="target-content"]').text(); 的返回值 - 似乎您缺少return 或至少console.log()

标签: javascript node.js web-crawler cheerio


【解决方案1】:
  1. 首先因为你已经启动if (err) console.err(err);,我认为你不需要再次启动条件if(res.statusCode === 200)。但这是可选的
  2. 首先检查console.log(res.statusCode)以检查res.statusCode中包含的内容
  3. console.log( $('p[id="target-content"]').text();) 或像这样存储在变量中
 const result = $('p[id="target-content"]').text();
 console.log(result) //if still null, try ``console.log $('p[id="target-content"]').data`` again to check with other options, or ``console.log $('p[id="target-content"]')``
 return result 

希望这条线索可以帮到你

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-02-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多