Nokogiri在视图中显示数据

试图弄清楚我在应用程序/ 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页面:

    

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

您的控制器需要自己加载数据,或以某种方式从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返回一个NodeSet,它就像一个数组,但你真的想指向Node本身,这就是做什么的。 at等于search('...').first

然后你使用:

 label.css('#boutiqueList img') 

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

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

而使用label.css正确找到节点:

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

然后使用map打印输出值,但map用于在迭代数据时修改数组的内容。 p将返回它输出的值,但依赖于mapp的返回值是不好的forms。 相反,您应map以转换值,然后在需要时查看结果:

  @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 }