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
或根本没有输出。我感谢任何帮助。非常感谢你。
- 首先因为你已经发起了
if (err) console.err(err);
,我认为你不需要再次启动条件if(res.statusCode === 200)
。但这是可选的 - 首先检查
console.log(res.statusCode)
以检查res.statusCode
中包含的内容 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
或根本没有输出。我感谢任何帮助。非常感谢你。
- 首先因为你已经发起了
if (err) console.err(err);
,我认为你不需要再次启动条件if(res.statusCode === 200)
。但这是可选的 - 首先检查
console.log(res.statusCode)
以检查res.statusCode
中包含的内容 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
我希望这个线索可以帮到你