Javascript Cheerio:如何通过文本内容选择元素?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/34709765/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 16:46:06  来源:igfitidea点击:

Cheerio: How to select element by text content?

javascriptjquery-selectorscheerio

提问by MarcoS

I have some HTML like this:

我有一些这样的 HTML:

<span id="cod">Code:</span> <span>12345</span>
<span>Category:</span> <span>faucets</span>

I want to fetch the category name ("faucets"). This is my trial:

我想获取类别名称(“水龙头”)。这是我的试验:

var $ = cheerio.load(html.contents);
var category = $('span[innerHTML="Category:"]').next().text();

But this doesn't work (the innerHTMLmodifier does not select anything).

但这不起作用(innerHTML修改器不选择任何内容)。

Any clue?

有什么线索吗?

回答by Josh Crozier

The reason your code isn't working is because [innerHTML]is an attribute selector, and innerHTMLisn't an attribute on the element (which means that nothing is selected).

您的代码不起作用的原因是因为[innerHTML]是属性选择器,而innerHTML不是元素上的属性(这意味着没有选择任何内容)。

You could filter the spanelements based on their text. In the example below, .trim()is used to trim off any whitespace. If the text equals 'Category:', then the element is included in the filtered set of returned elements.

您可以根据span元素的文本过滤元素。在下面的示例中,.trim()用于修剪任何空白。如果文本等于 'Category:',则该元素包含在过滤后的返回元素集中。

var category = $('span').filter(function() {
  return $(this).text().trim() === 'Category:';
}).next().text();


The above snippet will filter elements if their text is exactly 'Category:'. If you want to select elements if their text containsthat string, you could use the :containsselector (as pointed out in the comments):

如果元素的文本恰好是“类别:”,则上面的代码段将过滤元素。如果要选择文本包含该字符串的元素,则可以使用:contains选择器(如评论中指出的那样):

var category = $('span:contains("Category:")').next().text();

Alternatively, using the .indexOf()method would work as well:

或者,使用该.indexOf()方法也可以:

var category = $('span').filter(function() {
  return $(this).text().indexOf('Category:') > -1;
}).next().text();