0

我目前在我的Product模型中使用以下代码来读取和保存og:image零售网站的 s。

def photo_from_url(url)
  if !Nokogiri::HTML(open(url)).css("meta[property='og:image']").blank?
    photo_url = Nokogiri::HTML(open(url)).css("meta[property='og:image']").first.attributes["content"]
    self.photo = URI.parse(photo_url)
    self.save
  end
end

虽然这适用于大多数页面,但也有一些og:image会返回bad URI(is not URI?) 此类链接的示例是 H&M 零售网站上的以下链接格式。

http://lp.hm.com/hmprod?set=source[/model/2012/K71 05701 95313 06 0043 0.jpg],rotate[],width[],height[],x[],y[],type[STILL_LIFE_FRONT]&call=url[file:/product/facebook]

显然,这不是一个漂亮的链接(甚至 StackOverflow 的 Markdown 解析器也无法判断它是一个链接......),但当直接粘贴到浏览器中时它确实有效。

我该怎么做才能正确阅读这样的链接?

4

1 回答 1

2

哇,这看起来像一个讨厌的 URL。尽管 URL 方案不错,但我建议您只需使用以下方式转义您的 URL URI::Escape

irb(main):001:0> url = "http://lp.hm.com/hmprod?set=source[/model/2012/K71 05701 95313 06 0043 0.jpg],rotate[],width[],height[],x[],y[],type[STILL_LIFE_FRONT]&call=url[file:/product/facebook]"
=> "http://lp.hm.com/hmprod?set=source[/model/2012/K71 05701 95313 06 0043 0.jpg],rotate[],width[],height[],x[],y[],type[STILL_LIFE_FRONT]&call=url[file:/product/facebook]"
irb(main):002:0> uri = URI.escape url
=> "http://lp.hm.com/hmprod?set=source[/model/2012/K71%2005701%2095313%2006%200043%200.jpg],rotate[],width[],height[],x[],y[],type[STILL_LIFE_FRONT]&call=url[file:/product/facebook]"
irb(main):003:0> URI(uri)
=> #<URI::HTTP:0x000000024321d0 URL:http://lp.hm.com/hmprod?set=source[/model/2012/K71%2005701%2095313%2006%200043%200.jpg],rotate[],width[],height[],x[],y[],type[STILL_LIFE_FRONT]&call=url[file:/product/facebook]>
于 2012-12-02T23:36:00.580 回答