kaizty.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335
  1. # -*- coding: utf-8 -*-
  2. # 共两个步骤, 1, 将目标图片的信息拉到数据库(标题, 所有img的url), 2, 从数据库中读取对应目标站点的所有未下载过的img的url, 下载到本地
  3. # 需要安装psql, 并且 CREATE DATABASE collect; 运行会自动建表
  4. import sys
  5. import os
  6. import time
  7. import random
  8. import re
  9. import psycopg2
  10. sys.path.append(os.path.join(os.path.abspath(__file__).split('ResourceCollection')[0] + 'ResourceCollection'))
  11. import httpx
  12. from playwright.sync_api import sync_playwright
  13. target = 'kaizty'
  14. step = 1 # 1 = 获取img链接, 2 = 下载图片, 3 = 1 + 2, 4 = 调试
  15. local_proxy = 1
  16. title_selector = '#pack-view__inner > section.pack-view__header > h1' # 获取标题选择器
  17. img_selector = '#pack-view__inner > section.search-result > ul > li:nth-child({}) > div > a > img' # 获取图片的url
  18. img_count_selector = '#pack-view__inner > section.pack-view__header > p' # 获取图片总数选择器
  19. not_find_page_selector = 'body > div.page-navigation > a.next' # 当无法获取下一页时, 此选择器为最后一页
  20. project_root = os.path.join(os.path.abspath(__file__).split('ResourceCollection')[0] + 'ResourceCollection')
  21. psql_params = {
  22. "host": "home.erhe.link",
  23. "port": 55434,
  24. "user": "psql",
  25. "password": "psql",
  26. "dbname": "collect"
  27. }
  28. def open_browser(target_urls):
  29. all_data = {}
  30. for target_url in target_urls:
  31. pages = '?page={}'
  32. urls = []
  33. title = '' # 存放当前页面的title
  34. with sync_playwright() as playwright:
  35. if local_proxy:
  36. browser = playwright.chromium.launch(
  37. headless=True,
  38. proxy={"server": "http://127.0.0.1:7890"}
  39. )
  40. else:
  41. browser = playwright.chromium.launch(headless=True)
  42. context = browser.new_context(viewport={'width': 1280, 'height': 700})
  43. page = context.new_page()
  44. img_sequence_num = 1
  45. for page_count in range(30, 31):
  46. try:
  47. goto_url = target_url + pages.format(page_count)
  48. page.goto(goto_url, timeout=5000)
  49. page.wait_for_load_state('domcontentloaded')
  50. except Exception as e:
  51. print(e)
  52. print(f'页面加载失败:url:{goto_url}')
  53. page_source = page.content()
  54. title = page.title()
  55. img_list = re.findall('<meta property="og:image" content="(.*?)"', page_source)
  56. title = clean_string(title)
  57. for img_url in img_list:
  58. suffix = img_url.split('.')[-1]
  59. sequence = str(img_sequence_num).zfill(3)
  60. urls.append({
  61. 'url': img_url,
  62. 'file_title': title,
  63. 'serial': sequence,
  64. 'img': f'{title}_{sequence}',
  65. 'suffix': suffix
  66. })
  67. img_sequence_num += 1
  68. page.close()
  69. browser.close()
  70. if urls:
  71. all_data[title] = urls
  72. # 获取所有 url 数据之后, 存数据库
  73. return all_data
  74. def download_img(load_data, target_file_path):
  75. # 连接数据库, 准备反写下载状态
  76. conn = psycopg2.connect(**psql_params)
  77. cursor = conn.cursor()
  78. print('正在下载图片')
  79. for data in load_data:
  80. # 如果img文件存在, 即已经下载过, 直接跳过
  81. id = data['id']
  82. name = data['name']
  83. target_site = data['target_site'],
  84. file_title = data['file_title'].replace(' ', '_')
  85. set_name = data['set_name']
  86. serial = str(data['serial']).zfill(3)
  87. image_suffix = data['image_suffix']
  88. img_url = data['img_url']
  89. # 查看每个合集的文件夹是否存在, 不存在就创建
  90. title_file_path = os.path.join(target_file_path, file_title)
  91. if not os.path.exists(title_file_path):
  92. os.mkdir(title_file_path)
  93. img_name = f'{file_title}_{serial}.{image_suffix}' # 图片文件名
  94. img_file_path = os.path.join(str(title_file_path), img_name) # 图片完整路径
  95. if os.path.exists(img_file_path):
  96. # 当此 img 已存在本地时, 在 psql 将数据库状态改为已下载
  97. query = f"UPDATE {target} SET download_state = %s WHERE id = %s"
  98. cursor.execute(query, (True, id))
  99. conn.commit()
  100. print(f'图片 {img_file_path} 已存在。继续!')
  101. continue
  102. retry = 8
  103. while retry:
  104. try:
  105. resp = httpx.get(img_url, headers={
  106. "user-agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/130.0.0.0 Safari/537.36"
  107. })
  108. with open(img_file_path, 'wb') as f:
  109. f.write(resp.content)
  110. # 下载成功后, 在 psql 将数据库状态改为已下载
  111. query = f"UPDATE {target} SET download_state = %s WHERE id = %s"
  112. cursor.execute(query, (True, id))
  113. conn.commit()
  114. print(f'已下载:{img_name}')
  115. time.sleep(random.uniform(1, 2))
  116. break
  117. except Exception as e:
  118. print(f'下载图片失败:{img_name}。错误:{e} 重试: {retry}')
  119. retry -= 1
  120. time.sleep(random.uniform(3, 5))
  121. def save_data(data_item):
  122. conn = psycopg2.connect(**psql_params)
  123. cursor = conn.cursor()
  124. for k, v in data_item.items():
  125. for data in v:
  126. # 检查img_url是否重复
  127. cursor.execute("SELECT img_url FROM flaticon WHERE img_url = %s", (data['url'],))
  128. if cursor.fetchone() is None:
  129. # 插入数据
  130. cursor.execute("""
  131. INSERT INTO flaticon (name, target_site, file_title, set_name, serial, download_state, image_suffix, img_url)
  132. VALUES (%s, %s, %s, %s, %s, %s, %s, %s)
  133. """, (
  134. None,
  135. target,
  136. data['file_title'],
  137. None,
  138. data['serial'],
  139. False,
  140. data['suffix'],
  141. data['url']
  142. ))
  143. conn.commit()
  144. print(f"数据 {data['url']} 插入成功")
  145. else:
  146. print(f"数据 {data['url']} 已存在,未插入")
  147. # 关闭数据库连接
  148. cursor.close()
  149. conn.close()
  150. def load_data():
  151. # 连接数据库
  152. conn = psycopg2.connect(**psql_params)
  153. cursor = conn.cursor()
  154. # 查询download_state为false的所有数据
  155. query = f"SELECT * FROM {target} WHERE download_state = %s order by id asc"
  156. load_data_list = []
  157. try:
  158. # 执行查询
  159. cursor.execute(query, (False,))
  160. # 获取查询结果
  161. rows = cursor.fetchall()
  162. # 打印结果
  163. for row in rows:
  164. load_data_list.append(
  165. {
  166. 'id': row[0],
  167. 'name': row[1],
  168. 'target_site': row[2],
  169. 'file_title': row[3],
  170. 'set_name': row[4],
  171. 'serial': row[5],
  172. 'download_state': row[6],
  173. 'image_suffix': row[7],
  174. 'img_url': row[8]
  175. }
  176. )
  177. except psycopg2.Error as e:
  178. print(f"Database error: {e}")
  179. finally:
  180. # 关闭数据库连接
  181. cursor.close()
  182. conn.close()
  183. if load_data_list:
  184. return load_data_list
  185. else:
  186. print("没有需要下载的数据。")
  187. exit(0)
  188. def check_psql():
  189. # 连接数据库
  190. try:
  191. conn = psycopg2.connect(**psql_params)
  192. except Exception as e:
  193. print(f"无法连接到数据库:{e}")
  194. exit(1)
  195. # 创建cursor对象
  196. cur = conn.cursor()
  197. cur.execute("SELECT EXISTS(SELECT FROM pg_catalog.pg_tables WHERE schemaname = 'public' AND tablename = %s)",
  198. (target,))
  199. exist = cur.fetchone()[0]
  200. if not exist:
  201. # 如果不存在,则创建表
  202. cur.execute(f"""
  203. CREATE TABLE {target} (
  204. id SERIAL PRIMARY KEY,
  205. name VARCHAR(255),
  206. target_site VARCHAR(255),
  207. file_title VARCHAR(255),
  208. set_name VARCHAR(255),
  209. serial INT,
  210. download_state BOOLEAN,
  211. image_suffix VARCHAR(50),
  212. img_url VARCHAR(255)
  213. );
  214. """)
  215. print(f"表 '{target}' 创建成功。")
  216. # 提交事务
  217. conn.commit()
  218. # 关闭cursor和连接
  219. cur.close()
  220. conn.close()
  221. def check_local_downloads_dir():
  222. # 查看一下是否存在 downloads 文件夹, 不存在就创建一个
  223. download_file_path = os.path.join(str(project_root), 'downloads')
  224. if not os.path.exists(download_file_path):
  225. os.mkdir(download_file_path)
  226. target_file_path = os.path.join(download_file_path, target)
  227. if not os.path.exists(target_file_path):
  228. os.mkdir(target_file_path)
  229. return target_file_path
  230. def clean_string(string):
  231. string = string.replace('Kaizty Photos: ', '')
  232. string = string.split('|')[0]
  233. string = re.sub(r'[^\u4e00-\u9fff a-zA-Z0-9]', '', string)
  234. string = string.replace(' ', '_')
  235. if string.endswith('_'):
  236. string = string[:-1]
  237. return string
  238. if __name__ == "__main__":
  239. # 检查数据库
  240. check_psql()
  241. txt_file_name = 'target_link.txt'
  242. if not os.path.exists(txt_file_name):
  243. with open(txt_file_name, 'w') as file:
  244. file.write('')
  245. print('需要在 target_link.txt 中填写目标链接')
  246. exit(0)
  247. else:
  248. with open('target_link.txt', 'r') as f:
  249. targets = [target.strip() for target in f.readlines()]
  250. if not targets:
  251. print('在 target_link.txt 中未找到目标链接')
  252. exit(0)
  253. print(f'目标链接是:{targets}')
  254. if step == 1:
  255. all_data = open_browser(targets)
  256. save_data(all_data)
  257. elif step == 2:
  258. # 开始读取数据
  259. load_data = load_data()
  260. # 开始下载 img
  261. target_file_path = check_local_downloads_dir()
  262. download_img(load_data, target_file_path)
  263. print('下载完成, 程序退出')
  264. elif step == 3:
  265. # 保存 img 链接
  266. all_data = open_browser(targets)
  267. save_data(all_data)
  268. # 开始读取数据
  269. load_data = load_data()
  270. # 开始下载 img
  271. target_file_path = check_local_downloads_dir()
  272. download_img(load_data, target_file_path)
  273. print('下载完成, 程序退出')
  274. elif step == 4:
  275. # 调试
  276. pass
  277. else:
  278. pass