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)
全栈程序员-站长的头像全栈程序员-站长


相关推荐

  • goland激活码永久(破解版激活)

    goland激活码永久(破解版激活),https://javaforall.net/100143.html。详细ieda激活码不妨到全栈程序员必看教程网一起来了解一下吧!

    2022年3月16日
  • 前端页面图片加载失败显示默认图片

    前端页面图片加载失败显示默认图片方法有多种:1.首先说我用的,看代码//页面图片加载失败时默认显示统一处理document.addEventListener("error",function(e){  varelem=e.target;  if(elem.tagName.toLowerCase()=="img"){    elem.src="/image/General/errorDef…

    2022年6月2日
  • oracle手动创建数据库_oracle怎么建库

    oracle手动创建数据库_oracle怎么建库ORACLE手动建库ORACLE10GR2手动建库大致分为以下几个步骤编辑.bash_profile文件,设置环境变量创建所需目录结构创建初始化参数文件执行建库脚本下面以创建test数据库为例1、编辑.bash_profile文件,添加ORACLE_SID环境变量在.bash_profile文件中指定ORACLE_SIDexportORACLE_SID=test[oracle@targets…

    2022年10月27日
  • 成功解决TypeError: Cannot cast array data from dtype(‘float64’) to dtype(‘U32’) according to the rule ‘

    成功解决TypeError: Cannot cast array data from dtype(‘float64’) to dtype(‘U32’) according to the rule ‘成功解决TypeError:Cannotcastarraydatafromdtype(‘float64’)todtype(‘<U32’)accordingtotherule’目录解决问题解决思路解决方法解决问题TypeError:Cannotcastarraydatafromdtype(‘float64’)todtype(‘<U32’)accordingtotherule’safe’…

    2022年5月6日
  • mfc窗口置顶_mfc treecontrol

    mfc窗口置顶_mfc treecontrol版权声明:www.gudianxiaoshuo.com原创文章版权–古典小说网         WM_CONTEXTMENU消息用来响应鼠标右键消息,它响应的不是鼠标右键按下消息,也不是鼠标右键弹起消息而是鼠标右键依次按下弹起后触发的消息。          因此,若程序还响应了鼠标右键按下的消息OnRButtonDown,且在此响应函数中有模特对话

    2022年10月17日
  • 测试用例模板和例子[通俗易懂]

    测试用例模板和例子[通俗易懂]该范例已经包含一个测试用例的模板。项目/软件技术出口合同网络申领系统 (企业端)程序版本1.0.25   功能模块名Login 编制人  xxx   用例编号-TC-TEP_Login

    2022年7月17日

发表回复

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

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