# Scraping 3rd element with hpricot

**URL:** <https://www.ruby-forum.com/t/scraping-3rd-element-with-hpricot/155251>\
**Category:** Ruby\
**Created:** [December 9, 2008, 9:15pm UTC](https://www.ruby-forum.com/t/scraping-3rd-element-with-hpricot/155251 "2008-12-09T21:15:58Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![scorintha](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/s/278dde/32.png) [@scorintha](https://www.ruby-forum.com/u/scorintha)\
**Post date:** [December 9, 2008, 9:15pm UTC](https://www.ruby-forum.com/t/scraping-3rd-element-with-hpricot/155251/1 "2008-12-09T21:15:58Z")

</div>

I don’t know why I’m struggling with this (not a Ruby expert) but using  
the standard scraping example:

doc = Hpricot(@response)  
puts (doc/"#{xpath}").first.inner\_html  
puts (doc/"#{xpath}").last.inner\_html

What could I use instead of first or last to get the nth element?

Thanks!

---

<div class="post-metadata">

**Author:** ![scorintha](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/s/278dde/32.png) [@scorintha](https://www.ruby-forum.com/u/scorintha)\
**Post date:** [December 9, 2008, 11:51pm UTC](https://www.ruby-forum.com/t/scraping-3rd-element-with-hpricot/155251/2 "2008-12-09T23:51:58Z")

</div>

On Tue, Dec 9, 2008 at 2:09 PM, Mark N. [removed\_email\_address@domain.invalid](mailto:removed_email_address@domain.invalid) wrote:

> I don’t know why I’m struggling with this (not a Ruby expert) but using  
> the standard scraping example:
> 
> doc = Hpricot(@response)  
> puts (doc/“#{xpath}”).first.inner\_html  
> puts (doc/“#{xpath}”).last.inner\_html
> 
> What could I use instead of first or last to get the nth element?

Hpricot::Doc#search returns an instance Hpricot::Elements, which is a  
subclass of Array, so you can index it like any other array.

puts (doc/“#{xpath}”)[n].inner\_html # we’re counting from 0 here, so  
to get the 3rd element n=2

However, you will get an error with this if there are not enough  
elements returned by the search. So it might be better to do the  
search, validate that there are as many elements as you expect and  
then get the element you want by index. Like so:

puts x.inner\_html if x = (doc/“#{xpath}”)[n]

-Michael

---

<div class="post-metadata">

**Author:** ![scorintha](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/s/278dde/32.png) [@scorintha](https://www.ruby-forum.com/u/scorintha)\
**Post date:** [December 10, 2008, 2:44am UTC](https://www.ruby-forum.com/t/scraping-3rd-element-with-hpricot/155251/3 "2008-12-10T02:44:08Z")

</div>

Michael L. wrote:

> puts (doc/"#{xpath}")[n].inner\_html # we’re counting from 0 here, so  
> to get the 3rd element n=2

Thanks Michael, sometimes it’s right in front of you. I was trying to  
add a dot before [n]…

–Mark
