ruby on rails - Why does my extracted/scraped HTML code render as text? -
ruby on rails - Why does my extracted/scraped HTML code render as text? -
i want extract search form, this webpage, , render on "static_pages/home" page of rails app: codepen illustration of "static_pages/home"
steps taken:
i created next ruby script verify extract form:
require 'nokogiri' require 'open-uri' url = 'http://websoc.reg.uci.edu/perl/websoc' info = nokogiri::html(open(url)) form = data.xpath('//form[@action="http://websoc.reg.uci.edu/perl/websoc"]') puts form
shifting on rails, included nokogiri , openuri in gem file , used bundle install gems.
i created staticpages controller:
class staticpagescontroller < applicationcontroller def home require 'nokogiri' require 'open-uri' url = 'http://websoc.reg.uci.edu/perl/websoc' info = nokogiri::html(open(url)) @form = data.xpath('//form[@action="http://websoc.reg.uci.edu/perl/websoc"]') end end
and accompanying view:
<h1>staticpages#home</h1> <p>find me in app/views/static_pages/home.html.erb</p> <%= @form %>
the html code extracted rendered as text instead of html. seems either:
@form = data.xpath('//form[@action="http://websoc.reg.uci.edu/perl/websoc"]')
or
<%= @form %>
converts extracted html text. how can insert html content have extracted html , not text?
my research has suggested using net:http.
simply putting <%= @form.html_safe %>
, in view homecoming error. because @form
formatted text, not html. right this:
go static pages controller , change:
@form = data.xpath('//form[@action="http://websoc.reg.uci.edu/perl/websoc"]')
to @form = data.xpath('//form[@action="http://websoc.reg.uci.edu/perl/websoc"]').to_html.
now @form
stores html html, instead of text. render in view, need change:
<%= @form %>
to
<%= @form.html_safe %>
by default, rails convert <%= @form %>
text security precaution; not want malicious code embedded page. declaring @form.html_safe
tell rails html content intended and, hence safe. allows contents of @form
render in view html.
html ruby-on-rails ruby nokogiri screen-scraping
Comments
Post a Comment