Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
给 Pixiv 下载的图片重命名
#!/usr/bin/env python
#coding:utf-8
# Author: Sg4Dylan --<sg4dylan#gmail.com>
# Created: 12/31/2018
# ==========================================
# Pixiv 图片重命名
# ==========================================
# 使用方法: 把待处理的「文件夹」拖放到脚本上
import os
import re
import sys
import requests
from lxml.html import fromstring
from tqdm import tqdm
import multiprocessing
I_AM_CHINESE = True
target_root = ''
if len(sys.argv) > 1:
target_root = sys.argv[1]
proxies = {
'http': 'http://127.0.0.1:1080',
'https': 'http://127.0.0.1:1080'
}
session = requests.Session()
if I_AM_CHINESE:
session.proxies.update(proxies)
def proc_core(target_path):
illust_name = os.path.basename(target_path)
illust_dir = os.path.dirname(target_path)
re_pattern = r'^(\d{4,})_?'
if not re.search(re_pattern, illust_name):
return
illust_id = re.search(re_pattern, illust_name).group(1)
url = f'https://www.pixiv.net/member_illust.php?illust_id={illust_id}&mode=medium'
r = session.get(url)
if r.status_code != 200:
print(f'ERROR: {r.status_code} in {illust_name}')
return
tree = fromstring(r.content)
illust_raw_title = tree.findtext('.//title')
illust_fin_name = illust_raw_title \
.replace('のイラスト [pixiv]','') \
.replace('/','-')
illust_fin_name = re.sub(r'(.*?)', '', illust_fin_name)
illust_fin_name = re.sub(r'[\\/:*?"<>|\r\n]+', '-', illust_fin_name)
proced_name = re.sub(re_pattern, f'{illust_fin_name}_', illust_name)
confict_id = 0
while 1:
try:
if confict_id == 0:
os.rename(target_path,os.path.join(illust_dir, proced_name))
else:
os.rename(target_path,os.path.join(illust_dir, re.sub(r'_p\d.', f'_p{confict_id}.', proced_name)))
return
except FileExistsError:
confict_id += 1
def get_file_list():
file_path_list = []
for root, dirs, files in os.walk(target_root):
for name in files:
file_path_list.append(os.path.join(root, name))
return file_path_list
if __name__ == '__main__':
multiprocessing.freeze_support()
file_path_list = get_file_list()
with multiprocessing.Pool(processes=multiprocessing.cpu_count()) as exec_pool:
with tqdm(total=len(file_path_list),ascii=True) as pbar:
for i, _ in tqdm(enumerate(exec_pool.imap_unordered(proc_core,file_path_list))):
pbar.update()
os.system('pause')
@Mapaler

This comment has been minimized.

Copy link

Mapaler commented May 30, 2019

为什么不在保存的时候直接重命名呢?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.