Nokogiri:解析,提取和返回HTML表格中的内容

时间:2015-01-20 20:54:15

标签: ruby nokogiri

我正在尝试解析HTML表格。它基本上是HTML中的第六个<tr>标记:

<HTML>
<HEAD>
<TITLE>date</TITLE>
<meta http-equiv="Content-Type" content="text/html;charset=iso-8859-1">
</HEAD>
<BODY bgcolor="white">
<table border=0 cellpadding=0 cellspacing=0>
<tr>
    <td align=right colspan=2 id=ptitle name=ptitle>
        <font size=3>this is my title</font><br>
    </td>
</tr>
<tr>
    <td height=10 align=left colspan=2 valign=top>
        <table border=0 width="100%" cellpadding=0 cellspacing=0>
        <tr>
            <td width="50%" align=right><font size=2>this is my subtitle</font></td>
        </tr>
        </table>
    </td>
</tr>
    <td valign=top>
        <table border=0 cellpadding=0 cellspacing=0>
    <tr>
this is a line
</tr>
<tr>
this is a line</tr>
<tr>
this is a line</tr>
<tr>
this is a line</tr>
<tr>
this is a line</tr>
<tr>
this is a line</tr>
<tr>
this is a line</tr>
<tr>
this is a line</tr>
<tr>
this is a line</tr>

    </table>

    </td>
</tr>
</table>
<br>


</BODY>
</HTML>

我的Ruby代码如下所示:

require 'nokogiri'
require 'open-uri'
url = <website-name>
data = Nokogiri::HTML(open(url))
data.at('<tr>').next[6].text

但它不起作用。如何使用Nokogiri提取所有这些<tr>this is a line</tr>代码?

理想情况下,我希望将它包含在一个变量中并包含我想要的HTML,但它可以放到另一个网站中。

非常感谢!

1 个答案:

答案 0 :(得分:1)

这样:

data = Nokogiri::HTML(open(url))
rows = data.css("td[valign='top'] table tr") # All the <tr>this is a line</tr>
rows.each do |row|
  puts row.text # Will print all the 'this is a line'
end