|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
- from tkinter import *
- from tkinter import messagebox
- from tkinter import filedialog
- import tkinter.filedialog
- import urllib.request
- import urllib.parse
- import urllib.error
- import threading
- import inspect
- import ctypes
- import time
- import json
- import sys
- import os
- import re
- root = Tk()
- root.withdraw() #****实现主窗口隐藏
- root.update()
- lock = threading.Lock()
- k1=time.perf_counter()
- try:
- # 开头语
- k=time.strftime("%y-%m-%d %H:%M:%S")
- print("--------------------------------Python网络爬虫调用360图片网---------------------------------")
- print("------当前时间:",k)
- # 确定工作位置
- b="0"
- b=input("按Enter键确定工作位置(输入1默认当前位置)")
- if b!="1":
- #询问路径
- b=str(tkinter.filedialog.askopenfilename())
- weizhi=b
- n=weizhi.count("/")
- t=n-1
- while True:
- if n!=t:
- weizhi=weizhi[:-1]
- n=weizhi.count("/")
- else:
- break
- else:
- weizhi=os.getcwd()
- os.chdir(weizhi)
- print("------工作位置已确定!",weizhi)
- # 询问要搜索的内容
- a=input("请输入要搜索的图片:")
- print("------搜索词已确定!",a)
- # 创建工作文件夹
- b=a
- n=0
- while True:
- try:
- os.makedirs(weizhi+"\"+b)
- except FileExistsError:
- b=a
- b+=str(n+1)
- n+=1
- continue
- break
- print("------工作文件夹已确定!",weizhi+"\"+b)
- os.chdir(weizhi+"\"+b)
- print("------工作位置已转移到:",weizhi+"\"+b)
- # 编码搜索内容
- a=a.encode('utf-8')
- a=str(a)
- a=a.replace("\\x","%")
- a=a.upper()
- a="%"+a[3:-1]
- print("------搜索词已编码完成!",a)
- # 设置网址
- url='http://image.so.com/j?q='+a+'&src=srp&correct='+a+'&pn=60&ch=&sn=170&ps=168&pc=60&pd=1&prevsn=110&sid=91b72d98c21c1739643a4d14587f7db3&ran=0&ras=6&cn=0&gn=0&kn=50&comm=1'
- print("------搜索网址已确认!",url)
- # 设置head参数
- head={}
- head['User-Agent']="Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.132 Safari/537.36"
- head = urllib.parse. urlencode(head).encode('utf-8' )
- print("------head参数设置完成!",head)
- # 访问网址
- while True:
- try:
- print("------请求连接中......")
- req=urllib.request.Request(url,head)
- response = urllib.request.urlopen(req)
- except urllib.error.URLError as reason:
- print("------连接发生错误!")
- print("------请检查您的网络连接!")
- print("------错误原因是:",reason)
- print("------按Enter键重新连接")
- input()
- continue
- break
- print("------网址已连接成功!")
- html = response.read().decode('utf-8')
- print("------网址内容获取完毕!")
- # 内容分片
- v=html.split("},{")
- n=0
- d=[]
- print("------网址内容分片完成!")
- # 查找地址
- t=r'"img":"http:.{1,80}.jpg'
- for i in v:
- c=re.search(t,i)
- if not c==None:
- c=c.group()
- c=c[7:]
- c=c.replace("\\/\\/","//")
- c=c.replace("\\/","/")
- d.append(c)
- else:
- continue
- print("------图片地址筛选完毕!")
- # 搜索并下载
- k2=time.perf_counter()
- print("-------------------------------------进行文件下载任务--------------------------------------------")
- print("------共有",len(d),"条下载任务")
- print("----------------------------------------------------------------------------------------------------")
- yichang=[]
- yichang_num=[]
- # 创建下载函数
- def xiazai(name,url,number):
- try:
- response = urllib.request.urlopen(url)
- cat_img = response.read()
- with open(str(number)+'.jpg','wb') as f:
- f.write(cat_img)
- f.close()
- except Exception as reason:
- yichang.append(reason)
- yichang_num.append(number)
- print("------下载函数创建完毕!")
- # 创建超时处理函数
- def jishi():
- # 挂起下载线程
- fun_print("------下载线程正在挂起......")
- n=0
- for i in threads:
- n+=1
- i.setDaemon(True)
- i.start()
- fun_print("------"+str(n)+"条下载线程已全部挂起!")
- # 倒数计时
- time.sleep(50)
- fun_print("------超时处理线程:还有10秒,清空下载线程!")
- time.sleep(5)
- fun_print("------超时处理线程:还有5秒,清空下载线程!")
- time.sleep(2)
- n=4
- for i in range(3):
- n-=1
- fun_print("------超时处理线程:还有"+str(n)+"秒,清空下载线程!")
- time.sleep(1)
- # 清空线程
- fun_print("------超时处理线程:开始清空下载线程!")
- n=0
- for i in threading.enumerate():
- n+=1
- if n>3:
- stop_thread(i)
- fun_print("------超时处理线程:清空了:"+str(i))
- fun_print("------超时处理线程:下载线程清空完毕!")
- fun_print("------超时处理线程:正在下线......")
- print("------超时处理函数创建完毕!")
- # 创建中止线程函数
- def _async_raise(tid, exctype):
- """raises the exception, performs cleanup if needed"""
- tid = ctypes.c_long(tid)
- if not inspect.isclass(exctype):
- exctype = type(exctype)
- res = ctypes.pythonapi.PyThreadState_SetAsyncExc(tid, ctypes.py_object(exctype))
- if res == 0:
- raise ValueError("invalid thread id")
- elif res != 1:
- # """if it returns a number greater than one, you're in trouble,
- # and you should call it again with exc=NULL to revert the effect"""
- ctypes.pythonapi.PyThreadState_SetAsyncExc(tid, None)
- raise SystemError("PyThreadState_SetAsyncExc failed")
- def stop_thread(thread):
- _async_raise(thread.ident, SystemExit)
- print("------中止线程函数创建完毕!")
- # 创建输出函数
- def fun_print(name):
- lock.acquire()
- print(name)
- lock.release()
-
- # 创建下载线程
- threads = []
- for i in range(len(d)):
- threads.append(threading.Thread(target=xiazai,args=("线程"+str(i+1),d[i],i+1)))
- print("------下载线程创建完毕!")
-
- # 主程序代码
- # 挂起超时处理线程
- if __name__ == '__main__':
- t1=threading.Thread(target=jishi,args=(),name="超时处理线程")
- fun_print("------超时处理线程创建完毕!")
- t1.start()
- fun_print("------超时处理线程已挂起!")
- fun_print("------主进程在等待线程结束")
- # 进度条读条
- b=1000
- while True:
- a=threading.activeCount()
- a=a-3
- if a<b:
- fun_print("------汇报进度:下载进度:"+str(int(((len(d)-a)/len(d))*100))+"%, 剩余的下载线程数量:"+str(a))
- b=a
- if a==0:
- # 关闭超时处理线程
- a=threading.enumerate()
- if len(a)==3:
- stop_thread(a[2])
- break
- # 下载任务结束
- print("------所有下载线程均已结束!")
- k3=time.perf_counter()
- print("------下载任务完成!")
- print("----------------------------------------------------------------------------------------------------")
- k1=k3-k1
- k2=k3-k2
- c='------程序总用时:{:.3f}秒\n------下载任务用时:{:.3f}秒'
- print(c.format(k1,k2))
- print("------成功下载",len(d)-len(yichang),"张图片")
- print("------下载失败",len(yichang),"张图片")
- print("------图片下载位置在:",os.getcwd())
- os.chdir(weizhi)
- print("------工作位置已移动到",weizhi)
- print("----------------------------------------------------------------------------------------------------")
- while True:
- print("-------------------(输入'1'展开图片下载地址,'2'打开崩溃日志,'0'退出程序)-------------------")
- a=input(">>>")
- # '展开图片下载地址
- print("------注:图片地址序号与下载线程编号,图片序号,异常序号一一对应,方便参考")
- if a=="1":
- n=0
- for i in d:
- n+=1
- print("(",n,") ",i)
- # 打开崩溃日志
- elif a=="2":
- n=0
- print("-----------------------------------------下载任务崩溃日志-------------------------------------------")
- if yichang==[]:
- print("------没有发生过崩溃异常哦~~")
- else:
- print("------注:异常序号与下载线程编号,图片序号,图片地址序号一一对应,方便参考")
- print("------以下是下载程序捕获的所有异常及参数:")
- for i in yichang:
- print("(",yichang_num[n],") ",i)
- # 退出程序
- else:
- exit()
- # 捕捉终止快捷键
- except KeyboardInterrupt as reason:
- k=time.strftime("%y-%m-%d %H:%M:%S")
- print("----------------------------------------------------------------------------------------------------------")
- print("------ O__O …程序已无法运行!",k,reason)
- print("------您按下了CTRL+C键,程序被强制终止!")
- print("------如果您有任何使用问题,请报告:15838189794(微信QQ同号)")
- print("------如想继续运行,请退出后重新打开此程序")
- print("------ヾ ̄▽ ̄Bye~Bye~")
- input()
复制代码
|
|