Nokogiri 在视图中显示数据

Nokogiri displaying data in view

试图弄清楚如何显示我在 application/html 中抓取的文本和图像。 这是我的 app/scrape2.rb 文件

require 'nokogiri'
require 'open-uri'

url = "https://marketplace.asos.com/boutiques/independent-label"

doc = Nokogiri::HTML(open(url))

label = doc.css('#boutiqueList')

@label = label.css('#boutiqueList img').map { |l| p l.attr('src') }
@title = label.css("#boutiqueList .notranslate").map { |o| p o.text }

这是控制器:

class PagesController < ApplicationController
    def about
        #used to change the routing to /about
    end

      def index
         @label = label.css('#boutiqueList img').map { |l| p l.attr('src') }
         @title = label.css("#boutiqueList .notranslate").map { |o| p o.text }
    end

end

最后是 label.html.erb 页面:

<% @label.each do |image| %>
<%= image_tag image %>
<% end %>

我是否需要一些其他方法,而不是正确存储数组?

您的控制器需要自己加载数据,或者以某种方式从 scrape2.rb 中提取数据。控制器无权访问其他文件,除非指定(包含、扩展等)。

require 'nokogiri'
require 'open-uri'

class PagesController < ApplicationController

  def index 

     # Call these in your controller:
     url = "https://marketplace.asos.com/boutiques/independent-label"
     doc = Nokogiri::HTML(open(url))
     label = doc.css('#boutiqueList')

     @label = label.css('#boutiqueList img').map { |l| p l.attr('src') }
     @title = label.css("#boutiqueList .notranslate").map { |o| p o.text }
  end
end

您没有正确解析数据。

label = doc.css('#boutiqueList')

应该是:

label = doc.at('#boutiqueList')

#boutiqueList是一个ID,一个文档中一次只能有一个ID。 css return 是一个 NodeSet,就像一个数组,但你真的想指向节点本身,这就是 at 会做的。 at 等同于 search('...').first.

然后你使用:

label.css('#boutiqueList img')

这也是错误的。 label 应该已经指向包含 #boutiqueList 的节点,但是您希望 Nokogiri 查看该节点内部并找到带有 id="boutiqueList" 且包含 <img> 标签的其他节点。但是,同样,因为 #boutiqueList 是一个 ID,它不能在文档中出现多次,Nokogiri 找不到任何节点:

label.css('#boutiqueList img').size # => 0

而使用 label.css 正确找到 <img> 个节点:

label.css('img').size # => 48

然后您使用 map 打印出值,但 map 用于在迭代数组时修改数组的内容。 p 将 return 它输出的值,但是在 map 中依赖 p 的 returned 值是一种错误的形式。相反,您应该 map 转换值,然后 puts 如果需要查看结果:

 @label = label.css('#boutiqueList img').map { |l| l.attr('src') }
 puts @label

我不会使用 attr('src'),而是将第一行写为:

 @label = label.css('img').map { |l| l['src'] }

同样如此:

@title = label.css("#boutiqueList .notranslate").map { |o| p o.text }