# Parsing HTML tables

**URL:** <https://www.ruby-forum.com/t/parsing-html-tables/164391>\
**Category:** Ruby\
**Created:** [March 31, 2009, 8:59pm UTC](https://www.ruby-forum.com/t/parsing-html-tables/164391 "2009-03-31T20:59:42Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![ertai](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/e/258eb7/32.png) [@ertai](https://www.ruby-forum.com/u/ertai)\
**Post date:** [March 31, 2009, 8:59pm UTC](https://www.ruby-forum.com/t/parsing-html-tables/164391/1 "2009-03-31T20:59:42Z")

</div>

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” (

) I want to extract the information inside the  
colums . And then, I create a new object with these  
informations.

I done it by splitting my html source with the method split("

") 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…

---

<div class="post-metadata">

**Author:** ![ertai](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/e/258eb7/32.png) [@ertai](https://www.ruby-forum.com/u/ertai)\
**Post date:** [March 31, 2009, 9:47pm UTC](https://www.ruby-forum.com/t/parsing-html-tables/164391/2 "2009-03-31T21:47:40Z")

</div>

On Mar 31, 2:59 pm, Nicolas P. [removed\_email\_address@domain.invalid](mailto:removed_email_address@domain.invalid) wrote:

> informations.
> 
> I done it by splitting my html source with the method split(“”) 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

| One | Two | Three |

eohtml

doc = Nokogiri::HTML(html)

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

#—  
Output:  
One  
Two  
Three

---

<div class="post-metadata">

**Author:** ![ertai](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/e/258eb7/32.png) [@ertai](https://www.ruby-forum.com/u/ertai)\
**Post date:** [March 31, 2009, 10:35pm UTC](https://www.ruby-forum.com/t/parsing-html-tables/164391/3 "2009-03-31T22:35:57Z")

</div>

> 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 !
