我想提取的搜索表單,從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