【问题标题】:Get image file using ruby & capybara使用 ruby​​ 和 capybara 获取图像文件
【发布时间】:2012-10-23 19:38:53
【问题描述】:

是capybara通过HTTPS协议访问的页面上的图片标签:

<img src="path">

是否有任何方法可以使用 capybara 和任何类型的驱动程序从页面获取图像文件?

我不能使用像 File.read('path') 这样的东西,因为图像也只能通过 HTTPS 访问。我最近的研究让我找到了这样的解决方案:

  1. 访问页面
  2. 将页面保存为 png(webkit 驱动就有这么好用的能力)
  3. 裁剪图像

但我确实相信存在漂亮的解决方案。

编辑 1:

我已经尝试过 padde 的解决方案,但这里是响应正文:

<html><head><title>Object moved</title></head> 
    <body>
        <h2>Object moved to <a href=\"/Bledy/Blad404.aspx?aspxerrorpath=/CaptchaType.ashx\">here</a>.</h2> 
    </body>
</html>

编辑 2:

> curl -I image_path

5860cf30abf5d5480
HTTP/1.1 302 Found
Cache-Control: private
Content-Length: 168
Content-Type: text/html; charset=utf-8
Location: /Bledy/Blad404.aspx?aspxerrorpath=/CaptchaType.ashx
Server: Microsoft-IIS/7.5
X-AspNet-Version: 4.0.30319
X-Powered-By: ASP.NET
Date: Sat, 03 Nov 2012 17:18:55 GMT

【问题讨论】:

    标签: ruby selenium webkit capybara capybara-webkit


    【解决方案1】:

    如果我做对了,您可能想要的是来自 Ruby 的 HTTPS 请求。试试:

    require 'net/https'
    
    url = URI.parse('path')
    
    Net::HTTP.start(url.host, url.port, :use_ssl => true, :verify_mode => OpenSSL::SSL::VERIFY_NONE) do |http|
      res = http.get(url.request_uri)
      open("image.png", "wb") do |f|
        f.write(res.body)
      end
    end
    

    对于裁剪,您可以使用chunky_png(纯Ruby)或rmagick(需要ImageMagick)

    编辑:如果你想跟随重定向,你可以这样做

    require 'net/https'
    
    def process_image( content )
      # do your cropping here
    
      open("image.png", "wb") do |f|
        f.write(content)
      end
    end
    
    def fetch( url )
      Net::HTTP.start(url.host, url.port, :use_ssl => true, :verify_mode => OpenSSL::SSL::VERIFY_NONE) do |http|
        response = http.get(url.request_uri)
        case response.code
        when Net::HTTPRedirection
          fetch response['location']
        else
          process_image response.body
        end
      end
    end
    
    fetch URI.parse('path')
    

    【讨论】:

    • 证书验证失败。不知道为什么。据我了解,当解释器进入块时 - 建立了与该服务器的连接,并且在执行 http.get 时将发送所有存储的会话 cookie。无论如何,您为我指出了正确的搜索方向。谢谢!
    • 我猜您使用的是 Ruby 1.9,其中证书验证比以前的版本更严格。您可以使用:verify_mode =&gt; OpenSSL::SSL::VERIFY_NONE 解决此问题。我也更新了我的答案。
    • 是的,你是对的!但回复是:&lt;html&gt;&lt;head&gt;&lt;title&gt;Object moved&lt;/title&gt;&lt;/head&gt; &lt;body&gt;&lt;h2&gt;Object moved to &lt;a href=\"/Bledy/Blad404.aspx? aspxerrorpath=/CaptchaType.ashx\"&gt;here&lt;/a&gt;.&lt;/h2&gt; &lt;/body&gt;&lt;/html&gt; 和我之前的 wget 和 curl 结果类似。
    • 这可能意味着,您的浏览器正在重定向您。你可以试试stackoverflow.com/questions/6934185/…
    • 请在命令行中输入curl -I &lt;path&gt; 并显示结果,以便我为您提供帮助。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-08-29
    • 1970-01-01
    • 2014-06-10
    • 1970-01-01
    相关资源
    最近更新 更多