Ruby 使用Nokogiri解析表中的链接
这就是我想做的:Ruby 使用Nokogiri解析表中的链接,ruby,nokogiri,Ruby,Nokogiri,这就是我想做的: 查找具有特定内部文本的范围标记 获取此span标记后面的表 检索此表中的所有href链接 例如,我获取了Wiki页面的源代码: <h2><span class="mw-headline" id="Filmography">Filmography</span><span class="mw-editsection"> <span class="mw-editsection-bracket">[<
<h2><span class="mw-headline" id="Filmography">Filmography</span><span class="mw-editsection"> <span class="mw-editsection-bracket">[</span><a href="/w/index.php?title=Katie_Holmes&action=edit&section=10" title="Edit section: Filmography">edit</a><span class="mw-editsection-bracket">]</span></span></h2>
<table class="wikitable sortable plainrowheaders">
<caption>Film</caption>
<tr>
<th scope="col">Year</th>
<th scope="col">Title</th>
<th scope="col">Role</th>
<th scope="col" class="unsortable">Notes</th>
</tr>
<tr>
<td style="text-align:center;">1997</td>
<th scope="row"><i><span class="sortkey">Ice Storm, The</span><span class="vcard"><span class="fn"><a href="/wiki/The_Ice_Storm_(film)" title="The Ice Storm (film)">The Ice Storm</a></span> </span></i></th>
<td>Libbets Casey</td>
<td>First professional role</td>
</tr>
<tr>
<td style="text-align:center;">1998</td>
<th scope="row"><i><a href="/wiki/Disturbing_Behavior" title="Disturbing Behavior">Disturbing Behavior</a></i></th>
<td>Rachel Wagner</td>
<td><a href="/wiki/MTV_Movie_Award_for_Best_Breakthrough_Performance" title="MTV Movie Award for Best Breakthrough Performance">MTV Movie Award for Best Breakthrough Performance</a><br />
Nominated–<a href="/wiki/Saturn_Award_for_Best_Performance_by_a_Younger_Actor" title="Saturn Award for Best Performance by a Younger Actor">Saturn Award for Best Performance by a Younger Actor</a> </td>
</tr>
从影记录[]
胶卷
年
标题
角色
笔记
1997
冰暴
利贝茨·凯西
第一职业角色
1998
雷切尔·瓦格纳
提名——
我想查找带有文本“Filmography”的
标记,然后从下表中检索所有电影链接
我可以这样做吗?使用选择解决方案。(可能不是最有效的方法,但它有效)
这就是我一直在做的。但问题是,即使是“电视连续剧”、“奖项”等其他表格也有相同的跨度等级。所以,这段代码也在处理这些问题。我只想看电影。它仍然在做同样的事情(将
text.casecmp(“胶片”)
更改为text==“胶片”
。这应该行得通。是的,有很多方法比较字符串。很好,你成功了欢迎来到Stack Overflow!当你问一个关于代码的问题时,你应该向我们展示你在试图解决问题时编写的代码。将代码减少到最低限度,以演示你在使用it、 将输入数据减少到最低限度,并向我们展示您期望从代码中得到的结果。这有助于我们创建满足您需求的解决方案,而不是创建对我们有用但与您编写的代码无关的内容。
require 'open-uri'
require 'nokogiri'
page = Nokogiri::HTML(open("http://en.wikipedia.org/w/index.php?title=Katie_Holmes&action=edit&section=10"))
puts page.css('span.mw-headline#Filmography').text
page.css('table').each do |tab|
if tab.css('caption').text == "Film"
tab.css('th').css('a').each do |a|
puts "Title: #{a['title']} URL:#{a['href']}"
end
end
end
#=> Filmography
#=> Title: The Ice Storm (film) URL:/wiki/The_Ice_Storm_(film)
#=> Title: Disturbing Behavior URL:/wiki/Disturbing_Behavior
#=> .....So on