如何将Nokogiri Ruby爬虫结果存储至CSV、Google Sheets或SQL数据库?
三种存储方案的实现方法与可行性
这三种存储方式完全可行,下面是针对Ruby环境的具体实现方案,直接可以和你的Nokogiri爬虫整合:
一、存储到CSV
CSV是最轻量化的方案,无需额外依赖(Ruby标准库自带csv),适合快速导出数据。
实现步骤:
- 引入Ruby标准库的
csv模块 - 对每条爬取到的新闻数据,补充自增ID、时间戳、关键词字段
- 写入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支持。
实现步骤:
- 引入
sqlite3库 - 创建数据库和数据表(包含自增ID、时间戳等字段)
- 将爬取并补充字段的数据插入数据库
示例代码:
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。
实现步骤:
- 登录Google Cloud Console,创建项目并启用Google Sheets API
- 创建服务账号,下载JSON密钥文件(命名为
credentials.json) - 安装依赖库
google-api-client和googleauth - 编写代码认证并写入数据
示例代码:
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
相关产品推荐
相关产品推荐

