Ruby Ruby 如何获取跳转后的 URL

freemem · May 11, 2012 · Last by jamst replied at May 22, 2015 · 6767 hits

除了下面这个方法,还有什么更简单的办法?(我不想为此小事而装一个 httpclient gem) rails httpclient 获取转换后的地址: http://guduxiaoxian.iteye.com/blog/1156047

我用 nokogiri 做抓取时需要知道某 url 跳转后的 url,如: http://t.cn/h34YC 的真实地址是: http://www.guwendong.com/post/2008/social_media_algorithm_reddit.html 我要获取这个真实地址。

没有必要用 httpclient

require 'open-uri'
open("http://t.cn/h34YC") do |resp|
  puts resp.base_uri.to_s
end

#1 楼 @camel 太好了!thanks!

#1 楼 @camel nokogiri 本身有无此功能?如果这样就更帅了!

#1 楼 @camel 貌似这样写不行:

doc = Nokogiri::HTML(open("http://t.cn/h34YC").read.strip)
puts doc.base_uri.to_s

#4 楼 @freemem 这样写是不行的。 我的理解是: Nokogiri 只是用来分析网页源代码的,并不能处理 response 的其它信息,仅仅是源代码。 获取页面源码和分析 response 信息的是 open-uri,你那个跳转后的地址属于 response 信息。

#6 楼 @camel 谢谢,5 楼的问题怎么解决呢?open-uri 的 base_uri 方法也获取不了真实地址。 我现在用正则来提取其网址中存在的跳转地址:

link = "http://s.click.taobao.com/t_js?tu=http%3A%2F%2Fs.click.taobao.com%2Ft_9%3Fp%3Dmm_25282911_0_0%26l%3Dhttp%253a%252f%252fdetail.tmall.com%252fitem.htm%253fid%253d17271476630%26ref%3D"
reg = /(http.*=)?(http.*)/
turelink = URI.decode(URI.decode(link).gsub(reg,'\2'))
puts turelink

这个做法有效,但我觉得代码太丑陋,此外,不是所以网址都包含了跳转地址,还有没有更好的办法?

楼组,这个“不是所以网址都包含了跳转地址”最后有什么好的处理方法了吗?

You need to Sign in before reply, if you don't have an account, please Sign up first.