大家好,又见面了,我是你们的朋友全栈君。
cheerio作为node中jquery的替代品,拥有与jquery相似的api,甚至连详细文档的地址都指向api.jquery.com。但是由于执行环境的关系,并没有完全继承jquery中的方法。 对于这样的页面
<html>
<head></head>
<body>
<ul id="fruits">
<li>1</li>
<li>2</li>
</ul>
<ul id="others">
<li>1</li>
<li>2</li>
</ul>
</body>
</html>
在浏览器中,使用jquery获取所选取对象的包括本身标签的内容时,会用到下面的方法 ("......").prop("outerHTML") 例如若要去取id等于fruits的内容
但是这在cheerio中行不通。 网上搜索了一圈后基本都是一套翻译完的文档无限转载。。。还是自己动手写了两个方法。
var cheerio = require('cheerio');
const $ = cheerio.load('<html><head></head><body><ul id="fruits"><li>1</li><li>2</li></ul><ul id="others"><li>1</li><li>2</li></ul></body></html>');
console.log(cheerio.load('<div></div>')("div").html($("#fruits")).html());
既然它只能获取内容,那就造一个容器把它包进去再取。就是普通的jquery语法不解释。
改源码 核心的文件有两个。分别是cheerio包下的manipulation.js
exports.html = function(str) {
if (str === undefined) {
if (!this[0] || !this[0].children) return null;
return $.html(this[0].children, this.options);
}
var opts = this.options;
domEach(this, function(i, el) {
_.forEach(el.children, function(child) {
child.next = child.prev = child.parent = null;
});
var content = str.cheerio ? str.clone().get() : evaluate('' + str, opts, false);
updateDOM(content, el);
});
return this;
};
还有static.js
exports.html = function(dom, options) {
// be flexible about parameters, sometimes we call html(),
// with options as only parameter
// check dom argument for dom element specific properties
// assume there is no 'length' or 'type' properties in the options object
if (Object.prototype.toString.call(dom) === '[object Object]' && !options && !('length' in dom) && !('type' in dom))
{
options = dom;
dom = undefined;
}
// sometimes $.html() used without preloading html
// so fallback non existing options to the default ones
options = _.defaults(flattenOptions(options || {
}), this._options, defaultOptions);
return render(this, dom, options);
};
虽然完全搞不懂nodejs是怎么运行的(纯靠报错和ctrl+f硬找,我自己都意外的是在用断点之前就找到了解决方法),总之,在manipulation.js中添加这段代码
exports.outerHTML = function(str) {
return $.html(this[0], this.options);
}
然后这样调用也是可以的
var cheerio = require('cheerio');
const $ = cheerio.load('<html><head></head><body><ul id="fruits"><li>1</li><li>2</li></ul><ul id="others"><li>1</li><li>2</li></ul></body></html>');
console.log($("#fruits").outerHTML());
但是,这可能不符合规范,先用方法一凑合着吧。
发布者:全栈程序员栈长,转载请注明出处:https://javaforall.cn/150580.html原文链接:https://javaforall.cn