引入nokogiri:解析HTML表的没有开放标签
问题描述:
行我需要解析的HTML表这样的格式:引入nokogiri:解析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宝石,它可以扩大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安装会引发错误。 – 2014-09-30 22:40:02