简体   繁体   English

Ruby on Rails 无法保存用 Nokogiri 抓取的图像 src

[英]Ruby on Rails can't save image src scraped with Nokogiri

I'm trying to get the src value of an image (which is located on another website) with Nokogiri, save it in my database and use it to display this image in my view.我正在尝试使用 Nokogiri 获取图像(位于另一个网站上)的 src 值,将其保存在我的数据库中并使用它在我的视图中显示此图像。 But Rails raiseS this error message:但是 Rails 引发了这个错误信息:

Nil location provided.提供无位置。 Can't build URI.无法构建 URI。

here is my code in controller:这是我在 controller 中的代码:

def scrape

doc = Nokogiri::HTML(URI.open(page_url))
items = doc.css("j-wrapper-content")
images = doc.css("div.j-img")

images.each do |image|
  link = image.css("img").attr('src').to_s
  @product.image_url = "https://www.jacadi.fr#{link}"
end

items.each do |item|
  @product.name = item.css("h1").text
  @product.price = item.css("j-prd-price p").text.to_f
end

@product.save! end

and my code in view:和我的代码:

<% if product.picture.attached? %>
  <%= image_tag(product.picture, class: "card-pict") %>
<% elsif %>
  <%= image_tag(product.image_url, class: "card-pict") %>
<% else %>
  <%= image_tag("gift.png", class: "card-pict mini") %>
<% end %>

Finally found the solution: There were two issues :终于找到了解决方案:有两个问题:

  1. In the controller: The .在 controller 中: . were missing in front of the css selector so Nokogiri was unable to find them.在 css 选择器前面丢失,因此 Nokogiri 无法找到它们。

  2. In the view I've added the .present?在视图中我添加了.present? behind my product.image_url in my elsif statement.在我的 elsif 语句中的product.image_url后面。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM