You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用Ruby获取DuckDuckGo链接的最终重定向URL?

问题描述

当访问链接:

https://www.duckduckgo.com/?q=!ducky+goodreads+quotes+A+Promised+Land+Barack+Obama&t=h_&ia=web

最终会重定向到:

https://www.goodreads.com/work/quotes/86336100-a-promised-land

尝试使用以下Ruby代码获取最终重定向URL时,输出的仍是原DuckDuckGo链接:

res = Net::HTTP.get_response(URI('https://www.duckduckgo.com/?q=!ducky+goodreads+quotes+A+Promised+Land+Barack+Obama&t=h_&ia=web'))
puts res['location']

解决方案

原因分析

Net::HTTP.get_response默认仅返回第一次请求的响应,不会自动跟随后续的重定向跳转,所以你拿到的只是第一次跳转的Location头,而非最终目标URL。

方法一:使用Net::HTTP自动跟随重定向(Ruby 2.7+)

Ruby 2.7及以上版本支持follow_redirections参数,可直接让请求自动跟随所有重定向:

require 'net/http'

uri = URI('https://www.duckduckgo.com/?q=!ducky+goodreads+quotes+A+Promised+Land+Barack+Obama&t=h_&ia=web')
response = Net::HTTP.get_response(uri, follow_redirections: true)
puts response.uri.to_s

方法二:手动实现重定向跟随(兼容低版本Ruby)

如果使用的Ruby版本低于2.7,可以手动循环跟随重定向直到获取最终响应:

require 'net/http'

def get_final_redirect_url(initial_uri)
  current_uri = initial_uri
  loop do
    response = Net::HTTP.get_response(current_uri)
    case response
    when Net::HTTPRedirection
      current_uri = URI(response['location'])
    else
      return current_uri.to_s
    end
  end
end

initial_url = URI('https://www.duckduckgo.com/?q=!ducky+goodreads+quotes+A+Promised+Land+Barack+Obama&t=h_&ia=web')
puts get_final_redirect_url(initial_url)

方法三:使用Faraday库(更简洁的HTTP客户端)

Faraday是一个更易用的Ruby HTTP客户端,默认支持跟随重定向:

  1. 先安装gem:
gem install faraday
  1. 示例代码:
require 'faraday'

response = Faraday.get('https://www.duckduckgo.com/?q=!ducky+goodreads+quotes+A+Promised+Land+Barack+Obama&t=h_&ia=web')
puts response.env.url.to_s

内容的提问来源于stack exchange,提问作者sharataka

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.08 18:45:41