HTML前端连接go语言后段,前端字符串解析HTML-Go语言中文社区

一、parse5 - HTML解析器和序列化器

注意:默认情况下,所有函数都使用默认树适配器生成的树格式。 可以通过提供自定义树适配器实现来更改树格式。

方法:

1. parse - 解析 HTML 字符串,返回一个 Document

const parse5 = require('parse5');

const document = parse5.parse('

Hi there!');

console.log(document);

结果如下:

c1b9e33b21931afddc3191608303f6a7.png

注意: parse 方法返回的是一个 Document,即使参数是 HTML 节点字符串返回的树结构也是从 document 开始,HTML 节点作为 body 的子节点,例如:

const parse5 = require('parse5');

const document = parse5.parse('

Hi there!

');

console.log(document)

结果如下:

4b153e440672511e9d909ed965d5bb4f.png

2. parseFragment - 解析 HTML 片段,返回 DocumentFragment

const parse5 = require('parse5');

const documentFragment = parse5.parseFragment('

');

console.log(documentFragment);

结果如下:

7ac2befd82515e729e39c1af38d75bac.png

在解析的

const trFragment = parse5.parseFragment(documentFragment.childNodes[0], '

Shake it, baby');

console.log(trFragment)

结果如下:

2820ccc1c33ea9d896408138005f208f.png

3. serialize - 将 AST 节点序列化为 HTML 字符串,返回字符串

const document = parse5.parse('

Hi there!')

console.log(document)

const html = parse5.serialize(document)

console.log(html)

const body = parse5.serialize(document.childNodes[1].childNodes[1])

console.log(body)

const documentFragment = parse5.parseFragment('

Hello parse5!
')

console.log(documentFragment)

const div = parse5.serialize(documentFragment)

console.log(div)

结果依次:

a973ca29fa2ec2cded5dc1ef92219aa0.png

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值