Ruby: Get the redirected url using mechanize

This example is ideal for the case when actually you want to get the url that was redirected from another url. For example you have requested for url-1, and its redirected into url-2 and then into url-3. Now you want to get the url-3 on a variable. I have provided a small mechanize code for you.


agent = Mechanize.new { |a|
a.user_agent = 'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:24.0) Gecko/20100101 Firefox/24.0'
a.follow_meta_refresh = true
}

page = $agent.get("http://icfun.blogspot.com/")
page.uri.to_s



In this case it will print the blog's link itself as it doesn't have any redirection.


Comments