问题描述
我安装了Ruby和Mechanize。在我看来,Nokogiri可以做我想做的事,但我不知道该怎么做。
I installed Ruby and 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.
这个表?它只是vBulletin论坛网站的HTML的一部分。我试图保留HTML结构,但删除了一些文本和标签属性。我想要得到一些细节,例如:标题,作者,日期,时间,回复和视图。
What about this table
? It is just part of the HTML of a vBulletin forum site. I tried to keep the HTML structure but delete some text and tag attributes. I want to get some details per thread like: Title, Author, Date, Time, Replies, and Views.
请注意,HTML文档中的表格很少?我在一个具有 tbody
,< tbody id =threadbits_forum_251>
的特定表格之后。名字将永远是相同的(我希望)。我可以在代码中使用 tbody
和名称
吗?
Please note that there are few tables in the HTML document? I am after one particular table with its 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?
<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"}]
这篇关于如何使用Nokogiri解析HTML表格?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!