首页 > 解决方案 > 尝试使用 wget 或 curl 下载文件时如何避免重定向?

问题描述

我正在尝试从 url 获取/下载一些文件。我在 ruby​​ 中制作了一个小脚本来获取这些文件。按照脚本:

require 'nokogiri'
require 'open-uri'

(1..2).each do |season|
  (1..3).each do |ep|
    season = season.to_s.rjust(2, '0')
    ep = ep.to_s.rjust(2, '0')

    page = Nokogiri::HTML(open("https://some-url/s#{season}e{ep}/releases"))
    page.css('table.table tbody tr td a').each do |el|
      link = el['href']
      `curl "https://some-url#{link}"` if link.match('sujaidr.srt$')
    end
  end
end
puts "done"

但来自的回应curl是:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2 Final//EN">
<title>Redirecting...</title>
<h1>Redirecting...</h1>
<p>You should be redirected automatically to target URL: 
<a href="/some-url/friends-s0Xe0Y/releases">/some-url/s0Xe0Y/releases</a>.  If not click the link.

当我使用wget重定向页面时被下载。我试图设置用户代理但不起作用。仅当我尝试通过curl或其他 cli 下载文件时,服务器总是重定向链接,例如wget, aria2c,httpie等。我现在找不到任何解决方案。

我怎样才能做到这一点?


解决了

我决定使用Watir webdriver 来做到这一点。现在很好用。

标签: rubyurlcurldownloadwget

解决方案


如果您想下载文件,而不是执行重定向的页面,请尝试使用-L代码中的选项,例如:

curl -L "https://some-url#{link}"

来自curl男人:

-L, --location
              (HTTP) If the server reports that the requested page has moved to a different
              location  (indicated  with  a  Location:  header  and  a  3XX
              response  code),  this  option will make curl redo the request on
              the new place.

如果您正在使用ruby,而不是调用 curl 或其他 3rd 方工具,您可以 cat 使用以下内容:

require 'net/http'
# Must be somedomain.net instead of somedomain.net/, otherwise, it will throw exception.
Net::HTTP.start("somedomain.net") do |http|
    resp = http.get("/flv/sample/sample.flv")
    open("sample.flv", "wb") do |file|
        file.write(resp.body)
    end
end
puts "Done."

从示例出来的地方检查这个答案:https ://stackoverflow.com/a/2263547/1135424


推荐阅读