[英]How to save results into the database?
I created a web scraper. 我创建了一个网络刮板。
I'm struggling to save the results into the model's columns. 我正在努力将结果保存到模型的列中。
How do I push the results of the scrapped results into the columns? 如何将报废结果的结果推入列中?
Do you map it? 你有地图吗? Would like to understand it so I can eventually post to index perhaps ... or show previous saved results, etc ... 想了解它,以便最终可以发布索引...或显示以前保存的结果,等等...
Schema 架构
ActiveRecord::Schema.define(version: 20170308223314) do
# These are extensions that must be enabled in order to support this database
enable_extension "plpgsql"
create_table "links", force: :cascade do |t|
t.string "link_info"
t.string "date"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
end
end
The two columns that I'm trying to save to are the ones you see in the schema above: link_info
and date
... 我要保存到的两列是您在上面的架构中看到的列: link_info
和date
...
Current Controller 电流控制器
class LinksController < ApplicationController
def craigslist_scrape
require 'open-uri'
url = "https://losangeles.craigslist.org/search/web"
page = Nokogiri::HTML(open(url))
@craigslist_info = page.css("ul.rows")
@link_info = page.css("li.result-row p.result-info a.result-title.hdrlnk")
@date = page.css("li.result-row p.result-info time.result-date")
end
end
craiglist_scrape.html.erb craiglist_scrape.html.erb
<% @link_info.each_with_index do |link, index| %>
<h2><%= "Title of the job: #{link.text}" %></h2>
<p><%= "Date: #{@date[index].text}" %></p>
<% end %>
routes 路线
Rails.application.routes.draw do
root 'links#craigslist_scrape'
end
model 模型
class Link < ApplicationRecord
end
In the controller you can add: 在控制器中,您可以添加:
def craigslist_scrape
require 'open-uri'
url = "https://losangeles.craigslist.org/search/web"
page = Nokogiri::HTML(open(url))
@craigslist_info = page.css("ul.rows")
@link_info = page.css("li.result-row p.result-info a.result-title.hdrlnk")
@date = page.css("li.result-row p.result-info time.result-date")
@link_info.each_with_index do |link, index|
Link.new(:link => link.text, :date => @date[index].text).save
end
end
I'm rather new to Ruby and don't know much about Rails but what I always do when I'm trying to save something into a "database" is I create a hash. 我是Ruby的新手,对Rails不太了解,但是当我试图将某些内容保存到“数据库”中时我经常做的就是创建一个哈希。 For example: 例如:
database = {}
puts "What is your name?"
input = gets.chomp
puts "What's your age?"
input_2 = Integer(gets.chomp)
database[input.to_sym] = input_2
In the example above I create a hash called "database" and I ask the user for their name and age. 在上面的示例中,我创建了一个名为“数据库”的哈希,并询问用户的姓名和年龄。 Storing the user's name as the string value for database and their age as an integer value. 将用户名存储为数据库的字符串值,并将其使用期限存储为整数值。 I don't know if this helps at all, like I said I'm fairly new to Ruby. 我不知道这是否有帮助,就像我说我对Ruby刚起步一样。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.