为什么我提取/删除的HTML代码呈现为文本?

时间:2014-11-02 01:02:43

标签: html ruby-on-rails ruby nokogiri screen-scraping

我想从this webpage中提取搜索表单,并在我的Rails应用的“static_pages / home”页面上呈现:Codepen Example of "static_pages/home"

采取的步骤:

  1. 我创建了以下Ruby脚本来验证我是否可以实际提取表单:

    require 'nokogiri'
    require 'open-uri'
    
    url = 'http://websoc.reg.uci.edu/perl/WebSoc'
    data = Nokogiri::HTML(open(url))
    
    form = data.xpath('//form[@action="http://websoc.reg.uci.edu/perl/WebSoc"]')
    puts form 
    
  2. 转移到Rails,我在我的gem文件中包含Nokogiri和OpenURI,并使用bundle来安装gem。

  3. 我创建了一个StaticPages控制器:

    class StaticPagesController < ApplicationController
     def home
      require 'nokogiri'
      require 'open-uri'
    
      url = 'http://websoc.reg.uci.edu/perl/WebSoc'
      data = Nokogiri::HTML(open(url))
      @form = data.xpath('//form[@action="http://websoc.reg.uci.edu/perl/WebSoc"]')
     end
    end
    
  4. 以及随附的观点:

    <h1>StaticPages#home</h1>
    <p>Find me in app/views/static_pages/home.html.erb</p>
    <%= @form %>
    
  5. HTML代码已成功提取,但呈现的是as text而不是HTML。似乎要么:

    @form = data.xpath('//form[@action="http://websoc.reg.uci.edu/perl/WebSoc"]')
    

    <%= @form %>
    

    将提取的HTML转换为文本。如何将我提取的HTML内容作为HTML而不是文本插入?

    我的研究建议使用Net:HTTP

2 个答案:

答案 0 :(得分:1)

简单地在视图中放置<%= @form.html_safe %>将返回错误。这是因为@form被格式化为文本,而不是HTML。 要纠正这个:

  1. 转到静态页面控制器并更改:

    @form = data.xpath('//form[@action="http://websoc.reg.uci.edu/perl/WebSoc"]') 
    

    要     @form = data.xpath('// form [@ action =“http://websoc.reg.uci.edu/perl/WebSoc”]')。to_html。

  2. 现在@form将HTML存储为HTML而不是文本。要在视图中呈现此内容,我们需要更改:

    <%= @form %>
    

    <%= @form.html_safe %>
    
  3. 默认情况下,Rails会将<%= @form %>转换为文本作为安全预防措施;您不希望恶意代码嵌入到您的页面中。通过声明@form.html_safe,我们告诉Rails HTML内容是有意的,因此是安全的。这允许@form的内容在视图中呈现为HTML。

答案 1 :(得分:0)

您的问题表明您在Nokogiri::XML::NodeSet时收到了文字。

&#34; How do I scrape HTML between two HTML comments using Nokogiri?&#34;是一个类似的废除节点的问题。获得字符串html_string后,您可以使用html_string.html_safe