Forum: Ruby Parsing HTML tables

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
935a33e841895e2bfd99052be7931d4a?d=identicon&s=25 Nicolas Pioupiou (greyzlii)
on 2009-03-31 20:59
Hi everybody,

I'm searching for a way to write a beautidull code which parse an HTML
table.

In fact, the table is dynamic.
It always have three columns but have randoms lines.

In each "line" (<tr></tr>) I want to extract the information inside the
colums <td></td>. And then, I create a new object with these
informations.

I done it by splitting my html source with the method split("<tr>") and
use regexp to extract what I want. But this solution do not satisfied
me. It's unmaintanable.

However, I'm pretty sure that I could do more clever code...

Is there anyone has an idea, a clue a thought ?

Thanks.
PS: English is not my native langage...
134ea397777886d6f0aa992672a50eaa?d=identicon&s=25 Mark Thomas (Guest)
on 2009-03-31 21:47
(Received via mailing list)
On Mar 31, 2:59 pm, Nicolas Pioupiou <nicolas.e...@gmail.com> wrote:
> informations.
>
> I done it by splitting my html source with the method split("<tr>") and
> use regexp to extract what I want. But this solution do not satisfied
> me. It's unmaintanable.
>
> However, I'm pretty sure that I could do more clever code...
>
> Is there anyone has an idea, a clue a thought ?

Use a real parser. Example:

#---
require 'nokogiri'

html = <<eohtml
<html>
<body>
<table>
  <tr>
    <td>One</td><td>Two</td><td>Three</td>
  </tr>
</table>
</html>
eohtml

doc = Nokogiri::HTML(html)

doc.search('//tr').each do |line|
  puts line.search('td/text()')
end

#---
Output:
One
Two
Three
935a33e841895e2bfd99052be7931d4a?d=identicon&s=25 Nicolas Pioupiou (greyzlii)
on 2009-03-31 22:35
>
> Use a real parser.

Hi,

Thanks for your help.
I perfomerd tests with Hpricot (already included in my Ruby release))
I obtain good results. Great tool !

Thnks for your help !
This topic is locked and can not be replied to.