ruby - 尝试使用 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 来做到这一点。现在很好用。
解决方案
如果您想下载文件,而不是执行重定向的页面,请尝试使用-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
推荐阅读
- c# - SQLite 单元测试中的 FOREIGN KEY 约束失败
- makefile - 将我自己的头文件添加到 ATSAMA5D36 开发板库的代码中
- javascript - 如何使用 JS/React 检测没有外部库的移动设备或平板设备
- javascript - 具有多个变量的 ReactJS Radiobutton-Group
- xml - XmlElement.GetAttribute 不起作用
- xamarin.forms - span 中的绑定不起作用
- python - 无法导入烧瓶应用程序
- html - 用 opencpu 显示一个 visNetwork 对象
- git - 是否可以在另一个分支中将更改推送到主分支
- java-8 - Java 8 Stream collect:使用自定义 groupingBy 函数和 collectAndThen