在 Rails 中显示从 Nokogiri 抓取的数据? [英] Display data scraped from Nokogiri in Rails?

查看:50
本文介绍了在 Rails 中显示从 Nokogiri 抓取的数据?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我最近开始学习 Rails,并且正在尝试构建一个简单的应用程序,该应用程序从网站上抓取足球比赛并在我的 index.html 中显示数据.然后用户可以尝试预测赛程的比分.

I recently started learning Rails, and am trying to build a simple application which scrapes football fixtures from a website and displays the data in my index.html. Users can then try to predict the scoreline of the fixtures.

我设法使用 Nokogiri 将数据刮到了 fixtures.rb 文件中:

I managed to scrape the data into a fixtures.rb file using Nokogiri:

require 'nokogiri'
require 'open-uri'
doc = Nokogiri::HTML(open("http://www.bbc.co.uk/sport/0/football/21784836"))
doc.css("tr.row2").each do |item|
  puts item.at_css("td.left.first p").text
end

将它添加到 Ruby on Rails 应用程序的最简单方法是什么?我可以把它放到控制器中吗?我无法将文本完整粘贴为视图.

What would be the easiest way to add this into a Ruby on Rails application? Can I put this into the controller? I'm having trouble pasting the text in full as a view.

推荐答案

将其添加到数组中,然后在您的控制器中使用.

Add it to an array and then use it in your controller.

@football = []
doc.css("tr.row2").each do |item|
  @football << item.at_css("td.left.first p").text
end

然后在您的视图中您可以引用内容:

Then in your view you can reference the contents:

<% if @football %>
  <ul>
    <% @football.each do |foot| %>
      <li><%= foot %></li>
    <% end %>
  </ul>
<% end %>

这篇关于在 Rails 中显示从 Nokogiri 抓取的数据?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆