对路使用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的实现方法就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持phpstudy。
本文地址:https://www.stayed.cn/item/14572
转载请注明出处。
本站部分内容来源于网络,如侵犯到您的权益,请 联系我