批量下載對路網圖片並生成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就是那么簡單!


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2026 CODEPRJ.COM