user3131148
user3131148

Reputation: 353

How to get text from list items with Mechanize?

<div class="carstd">
  <ul>
    <li class="cars">"Car 1"</li>
    <li class="cars">"Car 2"</li>
    <li class="cars">"Car 3"</li>
    <li class="cars">"Car 4"</li>
  </ul>
</div>

I want strip the text from each list item with mechanize and print it out. I've tried puts page.at('.cars').text.strip but it only gets the first item. I've also tried

page.links.each do |x|
  puts x.at('.cars').text.strip

end 

But I get an error undefined method 'at' for #<Mechanize::Page::Link:0x007fe7ea847810>.

Upvotes: 0

Views: 1090

Answers (1)

pguardiario
pguardiario

Reputation: 54984

There's no links there. Links are a elements that get converted into special Mechanize objects. You want something like:

page.search('li.cars').text # the text of all the li's mashed together as a string

or

page.search('li.cars').map{|x| x.text} # the text of each `li` as an array of strings

Upvotes: 1

Related Questions