繁体   English   中英

Nokogiri:解析html表中没有打开标签的行

[英]Nokogiri: Parsing html table's rows with no open tag

我需要解析具有以下格式的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>'

如您所见,最后两行没有打开的<tr>标记。 当我尝试使用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>

当没有结束标记</tr> ,我已经在网络上找到了一些解决此问题的方法,但反之则没有。 是否有使用Nokogiri修复此问题的简单方法?

我认为这是由于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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM