【发布时间】: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