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. But Rails raiseS this error message:
Nil location provided. Can't build URI.
here is my code in 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 :
In the controller: The .
were missing in front of the css selector so Nokogiri was unable to find them.
In the view I've added the .present?
behind my product.image_url
in my elsif statement.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.