You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将Nokogiri Ruby爬虫结果存储至CSV、Google Sheets或SQL数据库?

三种存储方案的实现方法与可行性

这三种存储方式完全可行,下面是针对Ruby环境的具体实现方案,直接可以和你的Nokogiri爬虫整合:

一、存储到CSV

CSV是最轻量化的方案,无需额外依赖(Ruby标准库自带csv),适合快速导出数据。

实现步骤:

  1. 引入Ruby标准库的csv模块
  2. 对每条爬取到的新闻数据,补充自增ID、时间戳、关键词字段
  3. 写入CSV文件

示例代码:

require 'nokogiri'
require 'open-uri'
require 'csv'

# 假设这是你已有的爬虫逻辑,返回新闻数组
def crawl_news
  doc = Nokogiri::HTML(open('https://example-news-site.com'))
  doc.css('.news-item').map do |item|
    {
      title: item.css('.title').text.strip,
      url: item.css('a').attr('href').value
    }
  end
end

# 处理数据并写入CSV
news_list = crawl_news
timestamp = Time.now.strftime("%Y/%m/%d/%H") # 生成当前时间戳

CSV.open('news_output.csv', 'w', headers: ['ID', '标题', '链接', '时间戳', '关键词']) do |csv|
  news_list.each_with_index do |news, index|
    # 自增ID用索引+1,关键词可以手动指定或从标题提取(这里示例手动指定分类关键词)
    keywords = news[:title].include?('科技') ? '科技' : '综合'
    csv << [index + 1, news[:title], news[:url], timestamp, keywords]
  end
end

二、存储到SQL数据库(以SQLite为例)

SQLite无需额外服务,适合需要持久化查询的场景,Ruby标准库自带sqlite3支持。

实现步骤:

  1. 引入sqlite3库
  2. 创建数据库和数据表(包含自增ID、时间戳等字段)
  3. 将爬取并补充字段的数据插入数据库

示例代码:

require 'nokogiri'
require 'open-uri'
require 'sqlite3'

def crawl_news
  # 同上面的爬虫逻辑
  doc = Nokogiri::HTML(open('https://example-news-site.com'))
  doc.css('.news-item').map do |item|
    {
      title: item.css('.title').text.strip,
      url: item.css('a').attr('href').value
    }
  end
end

# 初始化数据库
db = SQLite3::Database.new('news.db')
db.execute <<-SQL
  CREATE TABLE IF NOT EXISTS news (
    id INTEGER PRIMARY KEY AUTOINCREMENT,
    title TEXT NOT NULL,
    url TEXT NOT NULL,
    created_at TEXT NOT NULL,
    keywords TEXT
  );
SQL

# 插入数据
news_list = crawl_news
timestamp = Time.now.strftime("%Y/%m/%d/%H")

news_list.each do |news|
  keywords = news[:title].include?('财经') ? '财经' : '其他'
  db.execute(
    "INSERT INTO news (title, url, created_at, keywords) VALUES (?, ?, ?, ?)",
    [news[:title], news[:url], timestamp, keywords]
  )
end

db.close

三、存储到Google Sheets

适合团队协作或需要在线查看的场景,需要用到Google Sheets API。

实现步骤:

  1. 登录Google Cloud Console,创建项目并启用Google Sheets API
  2. 创建服务账号,下载JSON密钥文件(命名为credentials.json)
  3. 安装依赖库google-api-client和googleauth
  4. 编写代码认证并写入数据

示例代码:

require 'nokogiri'
require 'open-uri'
require 'google/apis/sheets_v4'
require 'googleauth'
require 'googleauth/stores/file_token_store'
require 'fileutils'

def crawl_news
  # 同上面的爬虫逻辑
  doc = Nokogiri::HTML(open('https://example-news-site.com'))
  doc.css('.news-item').map do |item|
    {
      title: item.css('.title').text.strip,
      url: item.css('a').attr('href').value
    }
  end
end

# 配置Google Sheets API
OOB_URI = 'urn:ietf:wg:oauth:2.0:oob'
APPLICATION_NAME = 'News Crawler'
CREDENTIALS_PATH = 'credentials.json'
TOKEN_PATH = 'token.yaml'
SCOPE = Google::Apis::SheetsV4::AUTH_SPREADSHEETS

def authorize
  client_id = Google::Auth::ClientId.from_file(CREDENTIALS_PATH)
  token_store = Google::Auth::Stores::FileTokenStore.new(file: TOKEN_PATH)
  authorizer = Google::Auth::UserAuthorizer.new(client_id, SCOPE, token_store)
  user_id = 'default'
  credentials = authorizer.get_credentials(user_id)
  if credentials.nil?
    url = authorizer.get_authorization_url(base_url: OOB_URI)
    puts "Open the following URL in the browser and enter the resulting code after authorization:"
    puts url
    code = gets.chomp
    credentials = authorizer.get_and_store_credentials_from_code(
      user_id: user_id, code: code, base_url: OOB_URI
    )
  end
  credentials
end

# 准备数据并写入
service = Google::Apis::SheetsV4::SheetsService.new
service.client_options.application_name = APPLICATION_NAME
service.authorization = authorize

spreadsheet_id = '你的Google Sheets文档ID' # 替换成你的Sheet ID
range = 'Sheet1!A:E' # 写入的范围
news_list = crawl_news
timestamp = Time.now.strftime("%Y/%m/%d/%H")

# 构造写入数据(表头+每条新闻的字段)
values = [['ID', '标题', '链接', '时间戳', '关键词']]
news_list.each_with_index do |news, index|
  keywords = news[:title].include?('体育') ? '体育' : '综合'
  values << [index + 1, news[:title], news[:url], timestamp, keywords]
end

request = Google::Apis::SheetsV4::UpdateValuesRequest.new(
  values: values,
  value_input_option: 'RAW'
)
service.update_spreadsheet_value(spreadsheet_id, range, request)

补充说明:

  • 关键词字段如果需要自动提取,可以使用Ruby分词库(如rmmseg-cpp)对标题进行分词,再提取核心词汇
  • 时间戳如果需要爬取新闻本身的发布时间,可以在爬虫阶段从页面中提取,替换当前时间戳

内容的提问来源于stack exchange,提问作者kitodann

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.12 18:50:27