對路使用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(太養眼) 之一
然後是創建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就是那麼簡單!
以上這篇批量下載對路網圖片並生成html的實現方法就是小編分享給大家的全部內容了,希望能給大家一個參考,也希望大家多多支持。