8
8

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

任意のページからリンクが貼られている画像ファイルをダウンロード

Posted at
get_image.rb
#!/usr/bin/env ruby
# -*- coding: utf-8 -*-

require 'digest/sha1'
require 'nokogiri'
require 'pathname'
require 'parallel'
require 'open-uri'

dir = Pathname.new('/path/to/download')
dir.mkdir unless dir.exist?                       

html = Nokogiri::HTML(open(ARGV[0]))

Parallel.each(html.css('a'), :in_threads => 10) do |link|
  next unless link['href'] =~ /\.jpg$/
  filename = Digest::SHA1.hexdigest(link['href']) + '.jpg'
  filepath = dir + filename
  next if filepath.file?
  puts "Download... #{link['href']}"
  res = open(link['href']) rescue next
  if res.content_type =~ /^image/
    open(filepath, 'w').print res.read
  end
end
8
8
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
8
8

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?