0

我需要从 URL 解析一些参数到我的数据库和图像。

我使用回形针作为图像。

在 Rails 控制台中,我可以通过以下代码将图像添加到新帖子:

    image = Image.new
    image.image_from_url "http://yug-avto.ru/files/image/tradein/hyundai/877_VOLKSWAGEN_FAETON_2011_2_1366379491.jpg"
    image.watermark = true
    image.save!

在我的图像模型中

require "open-uri"
.......
def image_from_url(img_url)
  self.image = open(img_url)
end

并完成所有工作。但是当我使用 Nokogiri 时,此代码不起作用。

rake aborted!
No such file or directory - 
http://yug-avto.ru/files/image/tradein/peugeot/1027_Peugeot_308_2011_2_1370850441.jpg

我对 Nokogiri 解析的 rake 任务:

doc.xpath("//item").each do |ad|
 img = ad.at("image").text

 img1 = Image.new
 img1.image = open("#{img}") 
 img1.watermark = true
 img1.save!
end

在 Nokogiri 的 rake 任务中,我需要“nokogiri”和“open-uri”。

怎样成为?:))))

4

2 回答 2

3

谢谢TheChamp,你让我有了正确的想法。首先需要解析 URL,然后打开。

image = Image.new
ad_image_url = URI.parse("#{img}")
image.image = open(ad_image_url)
image.watermark = true
image.save!
于 2013-06-11T07:11:52.867 回答
3

这是来自我的解析器的代码片段......我猜你出错的地方是使用open(url)而不是parse(url).

picture = Picture.new(
    realty_id: realty.id,
    position: position,
    hashcode: realty.hashcode
)
# picture.image = URI.parse(url), edit: added open() as this worked for Savroff
picture.image = open(URI.parse(url))
picture.save!

此外,最好检查图像是否真的存在

picture_array.each do |url|

    # checks if the Link works
    res = Net::HTTP.get_response(URI.parse(url))

    # if so, it will add the Picture Link to the verified Array
    if res.code.to_i >= 200 && res.code.to_i < 400 #good codes will be betweem 200 - 399
        verified_array << url
    end
end
于 2013-06-10T13:26:52.490 回答