安装
npm install xmldom --save
代码示例
let DOMParser = require("xmldom").DOMParser;
function parseHtml() {
var html = `<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body></body>
</html>`;
// Get Document Object
var dom = new DOMParser().parseFromString(html, 'text/html');
// Find the corresponding object through the document operation
var titleElement = dom.getElementsByTagName("title");
if (titleElement.length > 0) {
console.log(titleElement[0].textContent);
}
}
parseHtml();
Document
附录
文件类型—MIME类型
安装
npm install jsdom --save
代码示例
let JSDOM = require('jsdom').JSDOM;
function parseHtml() {
var html = `<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
</body>
</html>`;
// Get Document Object
var dom = new JSDOM(html).window.document;
// Find the corresponding object through the document operation
var titleElement = dom.getElementsByTagName("title");
if (titleElement.length > 0) {
console.log(titleElement[0].textContent);
}
}
parseHtml();
Document