How to get text from list items with Mechanize?

1k views Asked by At
<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>.

1

There are 1 answers

0
pguardiario On

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