2015-01-20 52 views
0

我想解析一个HTML表格。它基本上是在HTML第六<tr>标签:Nokogiri:解析,提取并返回<tr> HTML表格中的内容

<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

欢迎堆栈溢出。这不是Sinatra代码,它是Ruby代码。而且,Sinatra标签是不需要的,因为你的问题中的代码不使用它。 – 2015-01-21 00:30:04

回答

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 
+0

这个工程!大!非常感谢! 现在我想获得整个html代码而不是仅仅内容(我认为它是nokogiri的一个特性)。任何机会获得每行的HTML? 非常感谢! – littleprinter 2015-01-21 06:38:58

+0

对'rows'变量,你有每个''的'html'。只要继续在每一行使用'.css('...')'方法来取消它们的html。 – Alfonso 2015-01-21 15:44:00

+0

太棒了。似乎工作,现在我试图得到它在我的HTML网站: 得到'/'做 url = data = Nokogiri :: HTML(open(url)) @rows = data.css(“td [ VALIGN =顶部]表TR“) ERB:鼓起 端 在鼓起视点有以下代码: HTML的东西 <%@rows [2]%> <%@rows [ 3]%> <%@rows [4]%> <%@rows [5]%> 因为我只想要第二行到第五行。 ()( – littleprinter 2015-01-21 22:31:13