Forum: Ruby Can I use Hpricot to parse data into different array elem?

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.
Christiaan V. (Guest)
on 2009-05-22 00:59
Hi,

I have a question about using Hpricot.

Say I have a file search.html that contains the following:

<ul class="search-results-item">
        <li class="search-item-title">


            <a
href="http://www.sheetmusicplus.com/title/Holst-G-Wind-Q...
G /Wind Quintet (Set)</a>
        </li>

          <span class="price">$21.95</span>

<li class="search-item-title">


            <a
href="http://www.sheetmusicplus.com/title/Holst-G-Wind-Q...
G /Wind Quintet(Score)</a>
        </li>

          <span class="price">$15.95</span>

And I want to use Hpricot to parse it and have each price matched with
its title.

If I do something like this

doc = open("F:/search.html") { |f| Hpricot(f) }
doc.search(".price").each do |price|
    prices = [price.inner_text]
    puts prices[0]

=>$21.95
$15.95

Then it seems that my search results are in an array, but that both
prices are in a single element in the array because both come up when I
ask for the element at [0]
I'm a ruby newbie--what am I missing?
Thanks very much
7stud -. (Guest)
on 2009-05-22 09:11
Christiaan Venter wrote:
> Hi,
>
> I have a question about using Hpricot.
>
> If I do something like this
>
> doc = open("F:/search.html") { |f| Hpricot(f) }
> doc.search(".price").each do |price|
>     prices = [price.inner_text]
>     puts prices[0]
>
> =>$21.95
> $15.95
>
> Then it seems that my search results are in an array, but that both
> prices are in a single element in the array because both come up when I
> ask for the element at [0]
> I'm a ruby newbie--what am I missing?
> Thanks very much

Not understanding loops?  Better variable names?


require 'rubygems'
require 'hpricot'

doc = open("html.txt") { |f| Hpricot(f) }

doc.search(".price").each do |price_tag|
  price = price_tag.inner_text
  puts price
end

--output:--
$21.95
$15.95
This topic is locked and can not be replied to.