cheerio获取outerHTML

cheerio获取outerHTMLcheerio作为node中jquery的替代品,拥有与jquery相似的api,甚至连详细文档的地址都指向api.jquery.com。但是由于执行环境的关系,并没有完全继承jquery中的方法。对于这样的页面<html> <head></head> <body> <ulid=”fruits”> <li>…

大家好,又见面了,我是你们的朋友全栈君。

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的内容
$("#fruits").prop("outerHTML")

但是这在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.net/150580.html原文链接:https://javaforall.net

(0)
全栈程序员-站长的头像全栈程序员-站长


相关推荐

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

关注全栈程序员社区公众号