【问题标题】:Ruby : cannot open a link that works in a web browserRuby:无法打开可在 Web 浏览器中使用的链接
【发布时间】:2017-05-14 15:05:49
【问题描述】:

我正在尝试从网站 mangafox 获取图片,图片显示在导航器中,但我不断收到 Ruby 错误

到目前为止,我已经尝试过:

require 'open-uri'
require 'pp'

def get_page(link)
  page = nil
  begin
    page = open(link, 'User-Agent' => "Ruby/#{RUBY_VERSION}")
  rescue Exception => e
    puts e.class.to_s
    puts e.message
  end
  return page
end

link = 'http://h.mfcdn.net/store/manga/9/14-116.0/compressed/Bleach-14-116[manga-rain]._manga_rain_bleach_ch116_01.jpg?token=24530ad3411b28ed7f5ef17f932e8713&ttl=1494853200'
# tried this after researching on internet because some characters are refused in links ( such as '[' or ']' )
link2 = link.gsub(/[\[\]]/) { '%%%s' % $&.ord.to_s(16) }.chomp

pp get_page(link)
pp get_page(link2)

但我得到了这个输出:

URI::InvalidURIError
错误的 URI(不是 URI?):http://h.mfcdn.net/store/manga/9/14-116.0/compressed/Bleach-14-116[manga-rain]._manga_rain_bleach_ch116_01.jpg?token=24530ad3411b28ed7f5ef17f932e8713&ttl=1494853200

OpenURI::HTTPError
403禁止

【问题讨论】:

    标签: ruby web-scraping open-uri


    【解决方案1】:

    在紧要关头可以使用 OpenURI,但最好使用更强大的网络库,例如 Net::HTTP 或 Typhoeus:

    response = Typhoeus.get('http://h.mfcdn.net/store/manga/9/14-116.0/compressed/Bleach-14-116[manga-rain]._manga_rain_bleach_ch116_01.jpg?token=24530ad3411b28ed7f5ef17f932e8713&ttl=1494853200')
    response.body #=> binary image data
    

    (注意:在分享之前对此进行了测试——它可以正常加载)

    【讨论】:

    • 非常感谢。将不得不查看错误处理文档
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-05-02
    • 2012-02-21
    • 2012-08-11
    • 2014-01-24
    • 2013-01-22
    • 1970-01-01
    相关资源
    最近更新 更多