解析HTML文档

时间:2015-06-11 15:59:07

标签: ruby nokogiri

我正在尝试使用Ruby和Nokogiri解析以下HTML:

<div class="vevent">
<table width="750"><tr>
<td width="25"> </td>
<td valign="top" width="200">
<font size="2" face="sans-serif">
<font color="black"><b>June 30, 2015</b></font>
<br>
<span class="dtstart"><span class="value-title" title="2015-06-30"></span></span><br><span class="summary"><font color="#92161" size="3"><b>Band Concert</b></font></span>
<br><font color="#333333">Event</font><br>
<br>
<br>
<br clear="left">Have a question? email us.<br>
<br></font>
</td>
<td valign="top" width="10"></td>
<td valign="top">
<br clear="left"><font color="#92161">111 Main Street</font><br>
<font color="#92161">Mainstreet, Ohio 55111</font>
<a rel="nofollow" href="http://maps.google.com/maps?f=q&amp;source=s_q&amp;hl=en&amp;geocode=&amp;q=%221700+111+MainStreet+NE+Mainstreet,+Ohio+55111%22" target="_blank"><font size="1" face="sans-serif">map link</font></a><br><br>
<font color="#92161"><font size="2" face="sans-serif">Telephone:</font> 3305551000</font><br><br>
Visit our website for complete information.<br><br>
Enjoy a summer evening concert on Main Street at 8pm. Doors and cash bar open at 7pm.<br><br>Look for more details and ticket sales to be released soon on our website<br>  <br><br>
<br>
</td>
</tr></table>
</div>

我想抓住最后一段文字:

Visit our website for complete information.<br><br>
Enjoy a summer evening concert on Main Street at 8pm. Doors and cash bar open at 7pm.<br><br>Look for more details and ticket sales to be released soon on our website<br>  <br><br>

到目前为止,这是我的代码:

events = doc.css("div.vevent")
events.collect do |row|
  row.css("td")[3]  
end

这将让我到第三个td,其中包含我正在寻找的文本,如下所示:

<td valign="top">
<br clear="left"><font color="#92161">111 Main Street</font><br>
<font color="#92161">Mainstreet, Ohio 55111</font>
<a rel="nofollow" href="http://maps.google.com/maps?f=q&amp;source=s_q&amp;hl=en&amp;geocode=&amp;q=%221700+111+MainStreet+NE+Mainstreet,+Ohio+55111%22" target="_blank"><font size="1" face="sans-serif">map link</font></a><br><br>
<font color="#92161"><font size="2" face="sans-serif">Telephone:</font> 3305551000</font><br><br>
Visit our website for complete information.<br><br>
Enjoy a summer evening concert on Main Street at 8pm. Doors and cash bar open at 7pm.<br><br>Look for more details and ticket sales to be released soon on our website<br>  <br><br>
<br>
</td>

然而,如果我在那个td上调用text,我会得到td中的所有文本。我只想要不在任何元素内的最后一点。我尝试使用XPath和parent,这样我就可以说“只是给我td里面的文本(没有嵌套在另一个元素里面)”但我无法让它工作。有人对此有任何想法吗?

2 个答案:

答案 0 :(得分:1)

试试此代码:doc.css('td')[3].css('> text()').to_s.strip

答案 1 :(得分:0)

我建议使用更灵活的xpath。 如果我理解正确,你会想:

  

我只想要不在任何元素

中的最后一位

所以,试试这个XPath:

//table//td[last()]/text()