對路使用ajax實(shí)現(xiàn)異步加載內(nèi)容,在它的js代碼中找到了相關(guān)代碼
type : 'POST', url : '/index.php/request/new_data2/' + times + '/'+locinfo[domn][0], dataType : 'json',
返回的json字符串是一個被序列化的數(shù)組,數(shù)組中存放的是字典,其中要關(guān)注的是dict['t']以及dict['i'],dict['t']存放了圖片的說明,dict['i']存放了圖片的url.知道了這些后就可以開始python腳本了
import相關(guān)模塊
# -*- coding: utf-8 -*-import urllib2 as urlimport jsonimport sysimport osfrom datetime import *
(已經(jīng)修復(fù)不能獲取指定類型的bug,請求的url中最后一個數(shù)字代表類型)
獲取json:index是下載的第幾頁,type是tws(太猥瑣) tr(太熱) tgx(太搞笑) tml(太萌了) tht(太好聽 tyy(太養(yǎng)眼) 之一
然后是創(chuàng)建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("../")主函數(shù),用于調(diào)用上面那幾個函數(shù)
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"一個循環(huán)體,獲取用戶輸入
while(True): print "輸入tws(太猥瑣) tr(太熱) tgx(太搞笑) tml(太萌了) tht(太好聽 tyy(太養(yǎng)眼) 之一/r/nexit:退出" type=raw_input() all_type=["tgx","tws","tyy","tr","tml","tht"] if type in all_type: print "鍵入下載頁數(shù):" lenght=raw_input() start(type,lenght) elif type=="exit": break else: print "/r/n輸入有誤/r/n"
ok完成了,腳本會在當(dāng)前目錄下生成一個以時間命名的html文件以及同名文件夾來存放圖片。
測試了一下,下載100多張圖片用了幾分鐘,所以呢我覺得不需要多線程來下載。
也可以稍稍修改下生成html的地方,變成分頁顯示,然后將網(wǎng)頁拖進(jìn)安卓手機(jī)里看也是不錯的
用python就是那么簡單!
以上這篇批量下載對路網(wǎng)圖片并生成html的實(shí)現(xiàn)方法就是小編分享給大家的全部內(nèi)容了,希望能給大家一個參考,也希望大家多多支持武林網(wǎng)。
新聞熱點(diǎn)
疑難解答