【问题标题】:Parse a HTML structure, what JS tools are available解析一个 HTML 结构,有哪些 JS 工具可用
【发布时间】:2013-07-04 14:13:26
【问题描述】:

我必须从网站的 HTML 表中获取信息。我想从 Node.ja 服务器向该网站发出 HTML 请求并解析 HTML 表。除了正则表达式之外,还有什么库或JS技术可以解析表格单元格中的数据吗?

对不起,我是编程新手。

【问题讨论】:

    标签: javascript html node.js html-parsing


    【解决方案1】:

    我会使用 JQuery。您可以像这样遍历所有表格数据:(这将提醒每个表格数据中的 html)

    $('td').each( function () { alert( $(this).html() } );
    

    或针对特定表:

    $('#specific_table_id.td').each( function () { alert( $(this).html() } );
    

    【讨论】:

    • node.js 上有加载 jQuery 的方法,但大多依赖 DOM 模拟,并不总是兼容所有 jQuery 插件。
    【解决方案2】:
    var doc = document.implementation.createDocument(null, your_downloaded_html_page_as_string, null);
    

    您可以使用普通的 DOM 函数,例如 getElementByTagName,firstChild,..etc 从您下载的 HTML 页面中获取实际数据。

    更多方法请参考Parse a HTML String with JS

    【讨论】:

      【解决方案3】:

      看看优秀的 Cheerio 库:

      https://github.com/MatthewMueller/cheerio

      示例在 Git 上。

      【讨论】:

        【解决方案4】:

        jsdom 是一个很棒的模块

        // Count all of the links from the Node.js build page
        var jsdom = require("jsdom");
        
        jsdom.env(
          "http://nodejs.org/dist/",
          ["http://code.jquery.com/jquery.js"],
          function (errors, window) {
            console.log("there have been", window.$("a").length, "nodejs releases!");
          }
        );
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2011-07-07
          • 1970-01-01
          • 2010-09-13
          • 2011-01-05
          • 1970-01-01
          • 2016-12-27
          • 2021-10-31
          相关资源
          最近更新 更多