使用 Cheerio 访问包含其他元素的 class 的文本
Accessing the text of a class that contains other elements using Cheerio
我只想访问 h1 的文本(在本例中为 H1 title is here
),但它会打印所有内容。我尝试在 text()
之前添加 .remove('.small-title')
,但没有成功。
<div class="modal-know>
<h1>
H1 title is here
<div class="small-title">
<a href="title-a">Click</a>
<a href="title-b">Click 2</a>
</div>
</h1>
</div>
Node.js代码
var newsTitle = ('.modal-know h1').text(); // prints out everything
console.log(newsTitle);
它说
including their descendants
这与 jQuery .text()
的行为相同
也许这个答案对您有帮助:jQuery: using .text() to retrieve only text not nested in child tags
这是我测试过的代码:
let newsTitle = $('.modal-know h1').contents()[0].nodeValue;
// solution 2:
// .clone() //clone the element
// .children() //select all the children
// .remove() //remove all the children
// .end() //again go back to selected element
// .text(); // prints out everything
//solution 3:
// .contents().filter(function(){
// return this.nodeType == 3;
// })[0].nodeValue;
console.log(newsTitle);
*在您的代码示例中 div modal-know class
中缺少一个 "
<div class="modal-know> -> <div class="modal-know">
我只想访问 h1 的文本(在本例中为 H1 title is here
),但它会打印所有内容。我尝试在 text()
之前添加 .remove('.small-title')
,但没有成功。
<div class="modal-know>
<h1>
H1 title is here
<div class="small-title">
<a href="title-a">Click</a>
<a href="title-b">Click 2</a>
</div>
</h1>
</div>
Node.js代码
var newsTitle = ('.modal-know h1').text(); // prints out everything
console.log(newsTitle);
它说
including their descendants
这与 jQuery .text()
的行为相同也许这个答案对您有帮助:jQuery: using .text() to retrieve only text not nested in child tags
这是我测试过的代码:
let newsTitle = $('.modal-know h1').contents()[0].nodeValue;
// solution 2:
// .clone() //clone the element
// .children() //select all the children
// .remove() //remove all the children
// .end() //again go back to selected element
// .text(); // prints out everything
//solution 3:
// .contents().filter(function(){
// return this.nodeType == 3;
// })[0].nodeValue;
console.log(newsTitle);
*在您的代码示例中 div modal-know class
中缺少一个 "<div class="modal-know> -> <div class="modal-know">