我遇到了麻煩解析裏面只有我發現的inner_html循環。我只想在該內容中再次使用XPath。我是新來的紅寶石,所以更好的解決方案在桌面上。如何使用XPath與nokogiri解析inner_html裏面的for循環
#!/usr/bin/ruby -w
require 'rubygems'
require 'nokogiri'
page1 = Nokogiri::HTML(open('mycontacts.html'))
# Search for nodes by xpath
page1.xpath('//html/body/form/div[2]/span/table/tbody/tr').each do |row|
#puts a_tag.content
puts "new row"
row_html = row.inner_html
puts row_html
puts ""
name = row_html.xpath("/td[1]").text
puts "name is " + name
end
我在for循環的每一行的輸出是一樣的東西:
new row
<th>First Name</th>
<th>Last Name</th>
<th>Phone</th>
下面是我得到的錯誤:
屏幕scraper.rb:20:在block in <main>': undefined method
xpath'for#(NoMethodError)
我想解析每個tr並獲取如下數據:Barney Rubble,Fred Flintstone
<table>
<tbody>
<tr>
<th>First Name</th>
<th>Last Name</th>
</tr>
<tr>
<td>Fred</td>
<td>Flintstone</td>
</tr>
<tr>
<td>Barney</td>
<td>Rubble</td>
</tr>
</tbody>
</table>
我願意接受建議。我認爲在for循環中只解析inner_html更容易,但如果有更簡單的方法可以在for循環中找到節點,那也可以。
感謝....
請分享你解析 –
我更新,它包括像什麼,我試圖做一個樣本HTML部分。 –