扩展 Cheerio
¥Extending Cheerio
Cheerio 已经提供了多种处理文档的方法,但有时你可能想要添加自定义功能。本指南将涵盖两种方法:添加自定义 CSS 伪元素并为 Cheerio 编写插件。
¥Cheerio already provides many ways of working with documents, but sometimes you may want to add custom functionality. This guide will cover two approaches: adding custom CSS pseudo elements and writing plugins for Cheerio.
添加自定义 CSS 伪类
¥Adding Custom CSS Pseudo-Classes
pseudos
选项是添加伪类的扩展点。它是从名称到函数字符串的映射。
¥The pseudos
option is the extension point for adding pseudo-classes. It is a
map from names to either strings of functions.
-
字符串值是一个选择器,元素必须匹配该选择器才能被选择。
¥A string value is a selector that the element must match to be selected.
-
调用函数时,将元素作为第一个参数,将可选参数作为第二个参数。如果返回 true,则该元素被选中。
¥A function is called with the element as its first argument, and optional parameters as the second. If it returns true, the element is selected.
以下是使用 pseudos 选项的示例:
¥Here is an example of using the pseudos option:
const $ = cheerio.load('<div class="foo"></div><div data-bar="boo"></div>', {
pseudos: {
// `:foo` is an alias for `div.foo`
foo: 'div.foo',
// `:bar(val)` is equivalent to `[data-bar=val s]`
bar: (el, val) => el.attribs['data-bar'] === val,
},
});
$(':foo').length; // 1
$('div:bar(boo)').length; // 1
$('div:bar(baz)').length; // 0
为 Cheerio 编写插件
¥Writing Plugins for Cheerio
加载文档后,你可以使用自定义插件方法扩展原型或等效的 fn
属性。这是一个例子:
¥Once you have loaded a document, you may extend the prototype or the equivalent
fn
property with custom plugin methods. Here is an example:
const $ = cheerio.load('<html><body>Hello, <b>world</b>!</body></html>');
$.prototype.logHtml = function () {
console.log(this.html());
};
$('body').logHtml(); // logs "Hello, <b>world</b>!" to the console
如果你使用 TypeScript,则应该为新方法添加类型定义:
¥If you're using TypeScript, you should add a type definition for your new method:
declare module 'cheerio' {
interface Cheerio<T> {
logHtml(this: Cheerio<T>): void;
}
}