【问题标题】:Nokogiri: Parsing html table's rows with no open tagNokogiri:解析没有打开标签的html表的行
【发布时间】:2014-09-29 15:17:30
【问题描述】:

我需要解析一个格式如下的html表格:

require 'nokogiri'

html_table = '<table>
    <tbody>
        <tr>
            <td>Some text in the first row!</td>
            <td>More text in the first row!</td>
        </tr>
        <td>Some text in the second row!</td>
        <td>More text in the second row!</td> </tr>
        <td>Some text in the third row!</td>
        <td>More text in the third row!</td>  </tr>
    </tbody>
</table>'

如您所见,最后两行没有打开的&lt;tr&gt; 标记。当我尝试使用puts Nokogiri::HTML(html_table).css('table tr') 获取所有三行时,代码被清除,最后两行变为td 节点:

<tr>
    <td>Some text in the first row!</td>
    <td>More text in the first row!</td>
</tr>

当没有结束标签&lt;/tr&gt; 时,我在网上找到了一些解决此问题的方法,但反之则不行。 有没有使用 Nokogiri 解决此问题的简单方法?

【问题讨论】:

    标签: html ruby nokogiri


    【解决方案1】:

    我认为这是由于 Nokogiri 的解析错误。 一个可能的解决方案是使用 Nokogumbo gem,它扩展了 nokogiri 的能力以更正确地解析。 通过以下方式安装:

    gem install nokogumbo
    

    而不是使用 nokogiri 你使用:

    require 'nokogumbo'# nokogumbo will also load Nokogiri, so no need to put: require 'nokogiri'
    Nokogiri::HTML5(source_code).css('table tr').each do |row|
      p row
    end
    

    请注意,您必须使用网站上的源代码,该源代码确实到处都有正确的标签。您可以使用网站的源代码如下,但当然要求网站页面上只有一个表格。

    require 'open-uri'
    source_code = open('http://www.url_to_website_I_want_to_parse.com')
    

    确保在课程开始时声明变量source_code

    【讨论】:

    • 完美运行!没有必要使用源代码,因为使用糟糕的代码就足够了。不得不说我在Linux上试过这个,因为在Windows上安装gem会报错。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-02-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-10-06
    相关资源
    最近更新 更多