有人知道Ruby Mechanize的缓存插件吗?

Dav*_*ker 3 ruby mechanize-ruby

我有一个基于Mechanize的Ruby脚本来抓取一个网站.我希望通过缓存在本地下载的HTML页面,使整个加速这一"调整输出 - >运行 - >调整输出"循环更快.我不想只为这个脚本在机器上安装外部缓存.理想的解决方案是插入Mechanize并透明地缓存提取的页面,图像等.

有人知道会有这样做的图书馆吗?或者另一种实现相同结果的方法(脚本第二次运行得更快)?

Mar*_*tto 8

做这种事情的一个好方法是使用(AWESOME)VCR gem.

以下是如何执行此操作的示例:

require 'vcr'
require 'mechanize'

# Setup VCR's configs.  The cassette library directory is where 
# all of your "recordings" are saved as YAML files.  
VCR.configure do |c|
  c.cassette_library_dir = 'vcr_cassettes'
  c.hook_into :webmock
end

# Make a request...
# The first time you do this it will actually make the call out
# Subsequent calls will read the cassette file instead of hitting the network
VCR.use_cassette('google_homepage') do
  a = Mechanize.new
  a.get('http://google.com/')
end
Run Code Online (Sandbox Code Playgroud)

如您所见...... VCR在第一次运行时将通信记录为YAML文件:

mario$  find tester -mindepth 1 -maxdepth 3
tester/vcr_cassettes
tester/vcr_cassettes/google_homepage.yml
Run Code Online (Sandbox Code Playgroud)

如果您想让VCR创建新版本的磁带,只需删除相应的文件即可.