批量该文件名:
import os
path = input('请输入文件路径(结尾加上/):')
# 获取该目录下所有文件,存入列表中
fileList = os.listdir(path)
n = 0
for i in fileList:
# 设置旧文件名(就是路径+文件名)
oldname = path + os.sep + fileList[n] # os.sep添加系统分隔符
# 设置新文件名
newname = path + os.sep + 'ZhaoLiying' + str(n + 1) + '.JPG'
os.rename(oldname, newname) # 用os模块中的rename方法对文件改名
print(oldname, '======>', newname)
n += 1
爬虫:
import urllib.request as ur
import os
import string
import threading
import re
import requests
import sys
def get_image(keyworld, pn, rn, type, i):
try:
url = ur.quote(
'https://image.baidu.com/search/acjson?tn=resultjson_com&ipn=rj&ct=201326592&is=&fp=result'
'&queryWord=' + keyworld + '&cl=2&lm=-1&ie=utf-8&oe=utf-8&adpicid=&st=-1&z=&ic=0&word=' + keyworld +
'&s=&se=&tab=&width=&height=&face=0&istype=2&qc=&nc=1&fr=&pn=' + str(pn) + '&rn=' + str(
rn) + '&gsm=1e&1529504588260=',
safe=string.printable)
req = ur.Request(url)
req.add_header("User-Agent", "Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:47.0) Gecko/20100101 Firefox/47.0")
html1 = ur.urlopen(url, timeout=600).read()
html1 = str(html1)
pat1 = '"thumbURL":".+?",'
pat2 = 'https:.+?.jpg'
thumbURLs = re.compile(pat1).findall(html1)
imageURLs = re.compile(pat2).findall(str(thumbURLs))
save_dir = type + '/' + type + i + '/'
if os.path.exists(save_dir) is False:
os.makedirs(save_dir)
num = 1
for index, imageurl in enumerate(imageURLs):
try:
data = ur.urlopen(imageurl, timeout=20).read()
fd = open(save_dir + type + '_' + str(pn) + '_' + str(index) + '.jpg', "wb")
fd.write(data)
fd.close()
sys.stdout.write('下载成功%s\r' % num)
sys.stdout.flush()
num = num + 1
except Exception as e:
print('保存图片异常:' + e)
except Exception as e:
print('获取图片url异常:' + e)
if __name__ == '__main__':
ai = input("Input key: ")
bi = input("Input num: ")
for i in range(int(bi)):
get_image(ai, i * 50, 50, ai, str(i))
# tA = ThreadA()
# tA.start()