Skip to content

Instantly share code, notes, and snippets.

@magicdawn
Created September 11, 2014 07:35
Show Gist options
  • Save magicdawn/118a656dea476343e5e6 to your computer and use it in GitHub Desktop.
Save magicdawn/118a656dea476343e5e6 to your computer and use it in GitHub Desktop.
tieba image downloader
# coding:utf-8
require "net/http"
require "win32console"
require "term/ansicolor"
require "nokogiri"
# require "iconv"
class String
include Term::ANSIColor
end
# config
ExampleUrl = "http://tieba.baidu.com/p/3287469841"
Debug = true
ImageDir = "images"
# decide url
if Debug
url = ExampleUrl
elsif ARGV[0] != nil or ARGV[0] != ''
url = ARGV[0]
else
puts "\
Usage : ruby tieba.rb #{ExampleUrl}\
".cyan
exit
end
# images 文件夹
if not Dir.exists? ImageDir
require "fileutils"
FileUtils.mkdir_p ImageDir
end
# request
res = Net::HTTP.get_response(URI(url))
res.body.force_encoding "GBK"
srcs = []
doc = Nokogiri::HTML(res.body)
imgs = doc.css("img.BDE_Image")
imgs.each do |img|
# puts img["src"]
srcs.push img['src']
end
def download(src,filename)
res = Net::HTTP.get_response URI(src)
File.open(filename,"wb+") { |f|
f.write res.body
}
end
index = 0
srcs.each { |src|
index += 1
download src,"#{ImageDir}/#{index}.jpg"
puts "第#{index}张下载完成:#{src}".encode('gbk') #中文控制台
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment