parse5-find-child
介绍
一个在parse5解析后的网页文档中,通过路径查找相关节点的工具,支持精确路径匹配和模糊路径匹配。
安装
npm i parse5-find-child -S
使用说明
假定需要查找的html文档如下所示:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>parse5-find-child test example</title>
</head>
<body>
<img class="top-image" src="boat.gif" alt="Big Boat">
<form class="simple-form" id="profile" action="">
<fieldset>
<legend>Personal information:</legend>
Name: <input type="text" size="30"><br>
E-mail: <input type="text" size="30"><br>
Date of birth: <input type="text" size="10">
</fieldset>
</form>
<div class="list-wrapper" id="drink">
<ul>
<li>Coffee</li>
<li>Milk</li>
</ul>
</div>
<div class="list-wrapper2" id="fruit">
<ul>
<li>Banana</li>
<li>Apple</li>
</ul>
</div>
<div class="table-wrapper">
<table id="contact" border="1">
<tr>
<th>First Name:</th>
<td>Bill Gates</td>
</tr>
<tr>
<th>Telephone:</th>
<td>555 77 854</td>
</tr>
<tr>
<th>Telephone:</th>
<td>555 77 855</td>
</tr>
</table>
</div>
</body>
</html>
通过指定路径查找节点,多层级路径用;
隔开。
每层路径支持4种查找方式,可联合使用多种方式,用,
隔开:
- 元素类型,比如
<div>
- class属性,比如
.list-wrapper
- id属性,比如
#fruit
- 通配符
*
可指定精确路径,比如<body>;<form>;<fieldset>
。
也可使用通配符*
指定模糊路径,比如.list-wrapper2;*;<li>
。
示例
import { parse } from 'parse5'
import findChild from 'parse5-find-child'
// 字符串html来自上述html文档
const doc = parse(html)
// 查找id为contact的节点
const theContactTable = findChild(doc, '#contact')
// 查找class为list-wrapper的节点
const theListWrapperDiv = findChild(doc, '.list-wrapper')
// 查找class为list-wrapper2的节点的所有li子节点
const out = findChild(doc, '.list-wrapper2;*;<li>')