批量下载对路网图片并生成html

  刚毕业找到工作,还没money给住的的地方连宽带(等发工资T.T),平时喜欢去对路上看看搞笑图片,于是便写了一个脚本来批量下载对路图片,然后在本地生产一个html文件,等下班后慢慢看,最终效果还不错,脚本使用python写的,源文件在此.

  对路使用ajax实现异步加载内容,在它的js代码中找到了相关代码

type : 'POST',
        url : '/index.php/request/new_data2/' + times + '/'+locinfo[domn][0],
        dataType : 'json',

  返回的json字符串是一个被序列化的数组,数组中存放的是字典,其中要关注的是dict['t']以及dict['i'],dict['t']存放了图片的说明,dict['i']存放了图片的url.知道了这些后就可以开始python脚本了

  import相关模块

# -*- coding: utf-8 -*-
import urllib2 as url
import json
import sys
import os
from datetime import *

  (已经修复不能获取指定类型的bug,请求的url中最后一个数字代表类型)

  获取json:index是下载的第几页,type是tws(太猥琐) tr(太热) tgx(太搞笑) tml(太萌了) tht(太好听 tyy(太养眼) 之一

def get_json(index,type):
    list=["tr","tht","tml","tyy","tgx","tws"]
    seq=list.index(type)+1
    res=url.urlopen(r"http://%s.dui.lu/index.php/request/new_data2/%s/%s"%(type,str(index),str(seq)))
    if res.headers.has_key("content-encoding"):
        print "gzip"
        fileobj=StringIO.StringIO()
        fileobj.write(res.read())
        fileobj.seek(0)
        gzip_file=gzip.GzipFile(fileobj=fileobj)
        context=gzip_file.read()
        #context=unicode(context,"utf8")
    else:
        #context=unicode(res.read(),"utf8")
        context=res.read()
    res.close()
    list=json.loads(context)
    return list

 

  然后是创建html文件

def create_html(alllist,name):
    html_head='<html><meta http-equiv="Content-Type" content="text/html; charset=utf-8" /><title>duilu</title><body>'
    html_end="</body></html>"
    f=open("%s.html"%(name),"w")
    f.write(html_head)
    for x in range(len(alllist)):
        f.write('<div><img src="%s/%s.gif"/>'%(name,str(x)))
        f.write('<p>%s</p></div>'%(alllist[x]['t'].encode('utf-8')))      
    f.write(html_end)
    f.close()

  下载图片

def download(list,dirname,index=0):
    os.chdir(dirname)
    for dict in list:
        imgurl=dict['i']
        text= dict['t']
        print index
        print imgurl
        print text
        res=url.urlopen(imgurl)
        img_type=".gif"
        content_type=res.headers["content-type"]
        if content_type=="image/jpeg":
            type=".jgp"
        filepath="%s"%(str(index)+img_type)
        f=open(filepath,"wb")
        f.write(res.read())
        f.close()
        res.close()
        index+=1
    os.chdir("../")

  主函数,用于调用上面那几个函数

def start(type,lenght):
    lenght=int(lenght)
    now=datetime.now()
    now=now.strftime("%m-%d %H.%M.%S")
    os.mkdir(type+now)
    
    alllist=[]
    for x in range(0,lenght):
        list=get_json(x,type)
        alllist.extend(list)
    create_html(alllist,type+now)
    download(alllist,type+now)
    print "\r\n\r\n==============OK==============\r\n\r\n"

  一个循环体,获取用户输入

while(True):
    print "输入tws(太猥琐) tr(太热) tgx(太搞笑) tml(太萌了) tht(太好听 tyy(太养眼) 之一\r\nexit:退出"
    type=raw_input()
    all_type=["tgx","tws","tyy","tr","tml","tht"]
    if type in all_type:
        print "键入下载页数:"
        lenght=raw_input()
        start(type,lenght)
    elif type=="exit":
        break
    else:
        print "\r\n输入有误\r\n"

 

ok完成了,脚本会在当前目录下生成一个以时间命名的html文件以及同名文件夹来存放图片.

测试了一下,下载100多张图片用了几分钟,所以呢我觉得不需要多线程来下载.

也可以稍稍修改下生成html的地方,变成分页显示,然后将网页拖进安卓手机里看也是不错的

 

用python就是那么简单!

posted @ 2012-08-17 22:02  FMN  阅读(2819)  评论(7编辑  收藏  举报