pldlt pldlt - 2 months ago 14
Ruby Question

Troubles with while loop and mechanize Ruby

I don't understand why my ruby code doesn't work with while and mechanize.

require 'mechanize'
mechanize = Mechanize.new
j = 1
while j <= 30 do
page = mechanize.get('http://mywebsite.com/events?page=#{j}'); j+=1
i = 1
while i <= 35 do
link = page.link_with(:id => /detail-link-#{i}/); i += 1
mylink = link.click
url = mylink.uri
title = mechanize.get(url)
puts title.at('.container h1')
end
end


My while loop
i
work but loop
j
doesn't go to the next page, I think my logic is not good but I don't know where the problem is.

Answer

You try to interpolate the page number into the page's URL. But interpolation only works with double quotes (").

Change

page = mechanize.get('http://mywebsite.com/events?page=#{j}'); j+=1

to

page = mechanize.get("http://mywebsite.com/events?page=#{j}"); j+=1
Comments