2014-09-26 63 views
0

行我需要解析的HTML表這樣的格式:引入nokogiri:解析HTML表的沒有開放標籤

require 'nokogiri' 

html_table = '<table> 
    <tbody> 
     <tr> 
      <td>Some text in the first row!</td> 
      <td>More text in the first row!</td> 
     </tr> 
     <td>Some text in the second row!</td> 
     <td>More text in the second row!</td> </tr> 
     <td>Some text in the third row!</td> 
     <td>More text in the third row!</td> </tr> 
    </tbody> 
</table>' 

正如你所看到的,最後兩行沒有開<tr>標籤。當我試圖讓使用puts Nokogiri::HTML(html_table).css('table tr')所有三排,代碼清理和最後兩行成爲td節點:

<tr> 
    <td>Some text in the first row!</td> 
    <td>More text in the first row!</td> 
</tr> 

我已經在網絡上找到一些方法來解決這個問題的時候沒有關閉標籤</tr>,但不是相反。 有沒有簡單的方法來解決這個使用Nokogiri?

回答

1

我認爲這是由於Nokogiri解析錯誤。 一個可能的解決方案是使用Nokogumbo寶石,它可以擴大nokogiri的解析能力。

gem install nokogumbo 

比而不是使用引入nokogiri你使用: 通過安裝此

require 'nokogumbo'# nokogumbo will also load Nokogiri, so no need to put: require 'nokogiri' 
Nokogiri::HTML5(source_code).css('table tr').each do |row| 
    p row 
end 

請注意,您必須從網站,並有正確的標籤在任何地方使用的源代碼。您可以按如下方式使用網站的源代碼,但它要求在課程頁面上只有一個表格。

require 'open-uri' 
source_code = open('http://www.url_to_website_I_want_to_parse.com') 

確保您在開始偏離航向聲明變量source_code

+0

它完美的作品!沒有必要使用源代碼,因爲使用錯誤的代碼就足夠了。我不得不說,我在Linux上試過這個,因爲Windows上的gem安裝會引發錯誤。 – 2014-09-30 22:40:02