当前位置: 首页 > 工具软件 > ParseHTML > 使用案例 >

JS 解析html字符串(xmldom, jsdom)

张玺
2023-12-01

使用第三方库解析html字符串

  • xmldom

    • 安装

      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类型

  • jsdom

    • 安装

      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
      
 类似资料: