[英]Ruby on Rails can't save image src scraped with Nokogiri
我正在嘗試使用 Nokogiri 獲取圖像(位於另一個網站上)的 src 值,將其保存在我的數據庫中並使用它在我的視圖中顯示此圖像。 但是 Rails 引發了這個錯誤信息:
提供無位置。 無法構建 URI。
這是我在 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
和我的代碼:
<% 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 %>
終於找到了解決方案:有兩個問題:
在 controller 中: .
在 css 選擇器前面丟失,因此 Nokogiri 無法找到它們。
在視圖中我添加了.present?
在我的 elsif 語句中的product.image_url
后面。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.