Ruby 批量下载图片文件

来源:互联网 发布:网络词扑街是什么意思 编辑:程序博客网 时间:2024/05/17 08:12
system("title PicDownloader")require 'open-uri'@fail=[] # The list of URLs failed to access@num = 0 # Total number of files to be downloaded@tsz = 0 # Total size of files to be downloadeddef down(uri,n)begindata = open(uri, 'User-Agent' => 'ruby'){|f| f.read}file = File.new("./6#{n}/#{File.basename(uri)}", 'w+')file.binmodefile << datafile.flushfile.close@num += 1@tsz += data.sizeputs "File:#{File.basename(uri)};Size:#{data.size} Bytes;100%"rescue Errnoputs "File:#{File.basename(uri)};Failed;Error:#{$!} *"@fail.push([uri,n,$!])rescueputs "File:#{File.basename(uri)};Failed;Error:#{$!} *"@fail.push([uri,n,$!])endendfor i in "01".."13"Dir.mkdir("6#{i}") unless FileTest.exist?("6#{i}") # Make a new directoryfor j in "01".."60"# Try to connect, if failed then jump out of this cycle.beginopen("http://www.hz2hs.net.cn/byweb/2015new/Pages/6#{i}/6#{i}#{j}1.jpg")rescuenextenddown("http://www.hz2hs.net.cn/byweb/2015new/Pages/6#{i}/6#{i}#{j}1.jpg",i)down("http://www.hz2hs.net.cn/byweb/2015new/Pages/6#{i}/6#{i}#{j}2.jpg",i)down("http://www.hz2hs.net.cn/byweb/2015new/Pages/6#{i}/6#{i}#{j}1big.jpg",i)endend# If failure(s) exist then try to remedyloop do@t = 1print "\nOperated OK. Please wait"while  @t < 7 ; sleep 1 ; print "." ; @t += 1 ; endif @fail==[] then break endputs "\nFailed URL(s) List:"@fail.each {|i| puts i[0]}puts "\nRetry?(y/n)"if gets.downcase != "y\n" then break endtmp = @fail@fail = []tmp.each {|i| down(i[0],i[1])} # Re-downloadendputs "Totally downloaded #{@tsz} bytes in #{@num} files."unless @fail == []# Set down the error message into a fileputs "#{@fail.size} file(s) out of #{@num + @fail.size} failed to download. Please refer to \"Err.txt\"."f = File.open("Err.txt","w")@fail.each {|k| f.puts k[0],k[2]}f.closeendprint "This process will be terminated in #{@t-=1} second(s)\r" while sleep(1) && @t > 0exit

0 0
原创粉丝点击