Display data scraped from Nokogiri in Rails?

2019-06-13 04:20发布

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.

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

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.

1条回答
ら.Afraid
2楼-- · 2019-06-13 04:50

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 %>
查看更多
登录 后发表回答