【发布时间】:2014-11-02 01:02:43
【问题描述】:
我想从this webpage 中提取搜索表单,并将其呈现在我的Rails 应用程序的“static_pages/home”页面上:Codepen Example of "static_pages/home"
采取的步骤:
-
我创建了以下 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 包含在我的 gem 文件中,并使用 bundle 来安装 gem。
-
我创建了一个 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 版本中写它的正确方法)
标签: html ruby-on-rails ruby nokogiri screen-scraping