最新消息: 电脑我帮您提供丰富的电脑知识,编程学习,软件下载,win7系统下载。

Cheerio在section标签中获取p标签的内容

IT培训 admin 9浏览 0评论

Cheerio在section标签中获取p标签的内容

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或根本没有输出。我感谢任何帮助。非常感谢你。

回答如下:
  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 

我希望这个线索可以帮到你

Cheerio在section标签中获取p标签的内容

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或根本没有输出。我感谢任何帮助。非常感谢你。

回答如下:
  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 

我希望这个线索可以帮到你

发布评论

评论列表 (0)

  1. 暂无评论