您可以通过打开 url、解析 html 并访问您指向的元素轻松获取描述,例如:
require 'nokogiri'
require 'open-uri'
url = 'https://www.olympic.org/usain-bolt'
doc = Nokogiri.HTML(open(url))
puts doc.css('section.text-content').text
既然你已经有了数据,那么你需要一个模型来存储,你可以创建一个新的,就像名为 Athlete 的例子一样,使用 rails generate 命令并迁移,就像
$ rails g model Athlete description:text
$ rails db:migrate
描述是一个文本数据类型属性,它允许你存储大文本,作为描述。
然后你需要插入它,或者更新它。您可以创建一个新记录,然后对其进行更新。在 Rails 控制台中,只需:
Athlete.create
这将创建一个没有描述的新运动员,但必须通过其 id 获取它。之后你就可以创建一个任务了,在lib/tasks文件夹下,你可以创建一个.rake扩展名的文件并添加你的代码,使用创建任务的方式,比如:
require 'nokogiri'
require 'open-uri'
namespace :feed do
desc 'Gets the athlete description and insert it in database.'
task athlete_description: :environment do
url = 'https://www.olympic.org/usain-bolt'
doc = Nokogiri.HTML(open(url))
description = doc.css('section.text-content').text
Athlete.find(1).update description: description
end
end
你有库,获取数据,并使用 ActiveRecord 更新记录,你可以轻松运行:
rails feed:athlete_description
# or
rake feed:athlete_description