[英]How do I parse an HTML table with Nokogiri?
I installed Ruby and Mechanize. 我安装了Ruby和Mechanize。 It seems to me that it is posible in Nokogiri to do what I want to do but I do not know how to do it.
在我看来,在Nokogiri中可以做我想做的事,但我不知道该怎么做。
What about this table
? 那张
table
呢? It is just part of the HTML of a vBulletin forum site. 它只是vBulletin论坛网站HTML的一部分。 I tried to keep the HTML structure but delete some text and tag attributes.
我试图保留HTML结构,但删除了一些文本和标记属性。 I want to get some details per thread like: Title, Author, Date, Time, Replies, and Views.
我想获取每个线程的一些详细信息,例如:标题,作者,日期,时间,答复和视图。
Please note that there are few tables in the HTML document? 请注意,HTML文档中的表格很少? I am after one particular table with its
tbody
, <tbody id="threadbits_forum_251">
. 我在一张带有
tbody
<tbody id="threadbits_forum_251">
特定表之后。 The name will be always the same (I hope). 名称将始终相同(我希望如此)。 Can I use the
tbody
and the name
in the code? 我可以在代码中使用
tbody
和name
吗?
<table >
<tbody>
<tr> <!-- table header --> </tr>
</tbody>
<!-- show threads -->
<tbody id="threadbits_forum_251">
<tr>
<td></td>
<td></td>
<td>
<div>
<a href="showthread.php?t=230708" >Vb4 Gold Released</a>
</div>
<div>
<span><a>Paul M</a></span>
</div>
</td>
<td>
06 Jan 2010 <span class="time">23:35</span><br />
by <a href="member.php?find=lastposter&t=230708">shane943</a>
</div>
</td>
<td><a href="#">24</a></td>
<td>1,320</td>
</tr>
</tbody>
</table>
#!/usr/bin/ruby1.8
require 'nokogiri'
require 'pp'
html = <<-EOS
(The HTML from the question goes here)
EOS
doc = Nokogiri::HTML(html)
rows = doc.xpath('//table/tbody[@id="threadbits_forum_251"]/tr')
details = rows.collect do |row|
detail = {}
[
[:title, 'td[3]/div[1]/a/text()'],
[:name, 'td[3]/div[2]/span/a/text()'],
[:date, 'td[4]/text()'],
[:time, 'td[4]/span/text()'],
[:number, 'td[5]/a/text()'],
[:views, 'td[6]/text()'],
].each do |name, xpath|
detail[name] = row.at_xpath(xpath).to_s.strip
end
detail
end
pp details
# => [{:time=>"23:35",
# => :title=>"Vb4 Gold Released",
# => :number=>"24",
# => :date=>"06 Jan 2010",
# => :views=>"1,320",
# => :name=>"Paul M"}]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.