寫(xiě)的有些簡(jiǎn)陋。。。。主要是根據(jù)相冊(cè)的地址來(lái)分析用戶ID和相冊(cè)ID,然后模擬請(qǐng)求相冊(cè)頁(yè)面,并提取所有照片,然后下載到本地的一個(gè)文件夾中。
#encoding: utf-8
require 'rubygems'
require 'mechanize'
class Renren
def initialize(e,p)
@agent = Mechanize.new
@page = @agent.get('http://3g.renren.com/')
@page = @page.form_with(:method => 'POST') do |r|
r.email = e
r.password = p
end.submit
end
def fetch_other_photo(album_link,foldername)
photo_urls = []
puts Iconv.conv("gb2312", "utf-8", "開(kāi)始分析相冊(cè)地址.....")
begin
user_id,album_id = parse_album_uri(album_link)
rescue
puts Iconv.conv("gb2312", "utf-8", "您的相冊(cè)地址不正確,請(qǐng)重新輸入!")
return
end
page = @agent.get("http://3g.renren.com/album/wgetalbum.do?id=#{user_id}owner=#{album_id}")
puts Iconv.conv("gb2312", "utf-8", "正在獲取所有照片地址.....")
loop do
page.links_with(:href => /http:\/\/3g\.renren\.com\/album\/wgetphoto\.do?/).each do |link|
photo = link.click
photo_urls photo.link_with(:text => "下載該圖").href
end
break if page.link_with(:text => "下一頁(yè)").nil?
page = page.link_with(:text => "下一頁(yè)").click
end
if photo_urls.length > 0
puts Iconv.conv("gb2312", "utf-8", "開(kāi)始下載相冊(cè).....")
unless File.directory?("#{foldername}")
Dir.mkdir("#{foldername}")
end
Dir.chdir("#{foldername}") do |path|
photo_urls.each do |photo_url|
@agent.get(photo_url) do |photo|
puts Iconv.conv("gb2312","utf-8","正在保存文件#{photo.filename}……已經(jīng)下載#{((photo_urls.index(photo_url)+1).to_f/photo_urls.length*100).to_i}%")
photo.save
end
end
end
puts Iconv.conv("gb2312","utf-8","相冊(cè)下載完畢.....")
else
puts Iconv.conv("gb2312","utf-8","相冊(cè)內(nèi)沒(méi)有照片喲~")
end
end
private
def parse_album_uri(uri)
uri = uri.chomp("#thumb")
uri = uri.split("?")
if uri.length > 1 and uri[1].include?("owner")
uri = uri[1].split("")
user_id = uri[0].split("=")[1]
album_id = uri[1].split("=")[1]
else
uri = uri[0].split("/")
album_id = uri[4]
user_id = uri[5].split("-")[1]
end
return user_id,album_id
end
end
print Iconv.conv("gb2312","utf-8","用戶名:")
username = gets.chomp()
print Iconv.conv("gb2312","utf-8","密碼:")
password = gets.chomp()
renren = Renren.new(username,password)
loop do
print Iconv.conv("gb2312","utf-8","粘貼相冊(cè)地址:")
uri = gets.chomp()
renren.fetch_other_photo(uri, username)
print Iconv.conv("gb2312","utf-8","按0退出程序,按其它鍵繼續(xù)下載其它相冊(cè):")
break if gets.chomp() == "0"
end