cheerio获取outerHTML

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());

但是,这可能不符合规范,先用方法一凑合着吧。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值