Rails中的Web爬虫从网页中提取链接和下载文件

the*_*ick 2 ruby ruby-on-rails web-crawler

我正在使用RoR,我将在我的应用程序中指定一个指向网页的链接,以下是我想要做的事情

(1)我想提取网页中的所有链接

(2)查找它们是否是pdf文件的链接(基本上是模式匹配)

(3)我想在链接中下载文件(例如pdf)并将它们存储在我的系统上.

我尝试使用Anemone,但它抓住了整个网站,这超出了我的需求,我如何下载相应链接中的文件?

干杯

sim*_*nwh 9

看看Nokogiri也是如此.

require 'nokogiri'
require 'open-uri'
doc = Nokogiri::HTML(open('http://www.thatwebsite.com/downloads'))

doc.css('a').each do |link|
  if link['href'] =~ /\b.+.pdf/
    begin
      File.open('filename_to_save_to.pdf', 'wb') do |file|
        downloaded_file = open(link['href'])
        file.write(downloaded_file.read())
      end
    rescue => ex
      puts "Something went wrong...."
    end
  end
end
Run Code Online (Sandbox Code Playgroud)

你可能想要做一些更好的异常捕获,但我想你明白了:)