我想提取的搜索表单,从this webpage,并使其在“static_pages /家”我的Rails应用程序的页面上:采取Codepen Example of "static_pages/home"为什么我的提取/抓取的HTML代码呈现为文本?
步骤:
我创建了下面的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
转移到Rails的,我包括引入nokogiri和OpenURI在我的宝石文件和用于捆绑安装的宝石。
我创建一个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
以及随附的视图:
<h1>StaticPages#home</h1> <p>Find me in app/views/static_pages/home.html.erb</p> <%= @form %>
的HTML代码被成功地抽取,但它呈现as text代替HTML。这似乎是两种:
@form = data.xpath('//form[@action="http://websoc.reg.uci.edu/perl/WebSoc"]')
或
<%= @form %>
将提取的HTML文本。我如何插入我已经提取为HTML的HTML内容而不是文本?
我的研究建议使用Net:HTTP。
是不是因为Rails会自动转义'<%= @form %>'中的html代码,对不对?如何使用像“<%= @ form.html_safe%>'? (对不起,我不知道用什么方式将它写入你的Rails版本) – gh640 2014-11-02 01:09:02
这会帮助你https://cbabhusal.wordpress.com/2015/08/28/ruby-on-rails-why-do-we -need-to-html_safe-string-why-html-tags-not-rendered/ – illusionist 2015-08-29 01:26:03