【问题标题】:How can I avoid redirecting when try to download a file using wget or curl?尝试使用 wget 或 curl 下载文件时如何避免重定向?
【发布时间】:2018-08-16 14:19:37
【问题描述】:

我正在尝试从 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 下载文件时,服务器总是重定向链接,例如 wgetaria2chttpie 等。我现在找不到任何解决方案。

我该怎么做?


已解决

我决定使用Watir webdriver 来执行此操作。现在很好用。

【问题讨论】:

  • 听起来好像缺少标头或 cookie。
  • Wget 自动跟随重定向。你确定 wget 不只是跟随重定向然后下载吗?
  • @Casper,这就是重点。 Wget 遵循重定向并下载重定向的 html 页面,而不是我想要的文件。明白了吗?
  • 我尝试使用curl -L --max-redirs 0 选项,但返回此curl: (47) Maximum (0) redirects followed。我知道-L option tells the Curl to follows the HTTP redirects。但如果没有它,Curl 将返回我被引用的 html 页面。
  • 如果服务器响应重定向,则文件不存在。如果服务器未在该地址提供它,则您无法下载它。这不是不遵循重定向的问题,这是服务器响应重定向而不是您期望的问题。我会先用浏览器和它的网络监视器来调试它。如果您使用浏览器下载它,它是否也被重定向?这应该在浏览器调试器中可见。

标签: ruby url curl download wget


【解决方案1】:

如果您想下载文件,而不是执行重定向的页面,请尝试在代码中使用选项 -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 方工具,你可以使用类似这样的东西:

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

【讨论】:

  • 我试试这个方法。但是 resp.body 只返回 302 Found 到正文中。
  • @SinésioNeto 尝试在命令行中使用curl -L http.... 来检查是否有效
  • 我试试。但不起作用。好吧,没关系。我使用像 Selenium 这样的 WebDriver 来执行此操作。感谢回复!
猜你喜欢
  • 1970-01-01
  • 2017-04-21
  • 1970-01-01
  • 1970-01-01
  • 2016-12-04
  • 2011-05-04
  • 1970-01-01
  • 2015-02-20
  • 1970-01-01
相关资源
最近更新 更多