Created
September 11, 2014 07:35
-
-
Save magicdawn/118a656dea476343e5e6 to your computer and use it in GitHub Desktop.
tieba image downloader
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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