kaizty.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341
  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 = 4 # 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(1, 2):
  46. # 检查一下当前页面是不是 404
  47. try:
  48. page.wait_for_selector(not_find_page_selector, state="attached", timeout=2000)
  49. print(f'总页数是 {page_count - 1} 在 url: {goto_url}')
  50. break
  51. except:
  52. pass
  53. try:
  54. goto_url = target_url + pages.format(page_count)
  55. page.goto(goto_url, timeout=5000)
  56. except Exception as e:
  57. print(e)
  58. print(f'页面加载失败:url:{goto_url}')
  59. page.wait_for_load_state('domcontentloaded')
  60. title = page.title()
  61. page_source = page.content()
  62. img_list = re.findall('<meta property="og:image" content="(.*?)"', page_source)
  63. title = clean_string(title)
  64. for img_url in img_list:
  65. suffix = img_url.split('.')[-1]
  66. sequence = str(img_sequence_num).zfill(3)
  67. urls.append({
  68. 'url': img_url,
  69. 'file_title': title,
  70. 'serial': sequence,
  71. 'img': f'{title}_{sequence}',
  72. 'suffix': suffix
  73. })
  74. img_sequence_num += 1
  75. all_data[title] = urls
  76. page.close()
  77. browser.close()
  78. # 获取所有 url 数据之后, 存数据库
  79. return all_data
  80. def download_img(load_data, target_file_path):
  81. # 连接数据库, 准备反写下载状态
  82. conn = psycopg2.connect(**psql_params)
  83. cursor = conn.cursor()
  84. print('正在下载图片')
  85. for data in load_data:
  86. # 如果img文件存在, 即已经下载过, 直接跳过
  87. id = data['id']
  88. name = data['name']
  89. target_site = data['target_site'],
  90. file_title = data['file_title'].replace(' ', '_')
  91. set_name = data['set_name']
  92. serial = str(data['serial']).zfill(3)
  93. image_suffix = data['image_suffix']
  94. img_url = data['img_url']
  95. # 查看每个合集的文件夹是否存在, 不存在就创建
  96. title_file_path = os.path.join(target_file_path, file_title)
  97. if not os.path.exists(title_file_path):
  98. os.mkdir(title_file_path)
  99. img_name = f'{file_title}_{serial}.{image_suffix}' # 图片文件名
  100. img_file_path = os.path.join(str(title_file_path), img_name) # 图片完整路径
  101. if os.path.exists(img_file_path):
  102. # 当此 img 已存在本地时, 在 psql 将数据库状态改为已下载
  103. query = f"UPDATE {target} SET download_state = %s WHERE id = %s"
  104. cursor.execute(query, (True, id))
  105. conn.commit()
  106. print(f'图片 {img_file_path} 已存在。继续!')
  107. continue
  108. retry = 8
  109. while retry:
  110. try:
  111. resp = httpx.get(img_url, headers={
  112. "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"
  113. })
  114. with open(img_file_path, 'wb') as f:
  115. f.write(resp.content)
  116. # 下载成功后, 在 psql 将数据库状态改为已下载
  117. query = f"UPDATE {target} SET download_state = %s WHERE id = %s"
  118. cursor.execute(query, (True, id))
  119. conn.commit()
  120. print(f'已下载:{img_name}')
  121. time.sleep(random.uniform(1, 2))
  122. break
  123. except Exception as e:
  124. print(f'下载图片失败:{img_name}。错误:{e} 重试: {retry}')
  125. retry -= 1
  126. time.sleep(random.uniform(3, 5))
  127. def save_data(data_item):
  128. conn = psycopg2.connect(**psql_params)
  129. cursor = conn.cursor()
  130. for k, v in data_item.items():
  131. for data in v:
  132. # 检查img_url是否重复
  133. cursor.execute("SELECT img_url FROM flaticon WHERE img_url = %s", (data['url'],))
  134. if cursor.fetchone() is None:
  135. # 插入数据
  136. cursor.execute("""
  137. INSERT INTO flaticon (name, target_site, file_title, set_name, serial, download_state, image_suffix, img_url)
  138. VALUES (%s, %s, %s, %s, %s, %s, %s, %s)
  139. """, (
  140. None,
  141. target,
  142. data['file_title'],
  143. None,
  144. data['serial'],
  145. False,
  146. data['suffix'],
  147. data['url']
  148. ))
  149. conn.commit()
  150. print(f"数据 {data['url']} 插入成功")
  151. else:
  152. print(f"数据 {data['url']} 已存在,未插入")
  153. # 关闭数据库连接
  154. cursor.close()
  155. conn.close()
  156. def load_data():
  157. # 连接数据库
  158. conn = psycopg2.connect(**psql_params)
  159. cursor = conn.cursor()
  160. # 查询download_state为false的所有数据
  161. query = f"SELECT * FROM {target} WHERE download_state = %s order by id asc"
  162. load_data_list = []
  163. try:
  164. # 执行查询
  165. cursor.execute(query, (False,))
  166. # 获取查询结果
  167. rows = cursor.fetchall()
  168. # 打印结果
  169. for row in rows:
  170. load_data_list.append(
  171. {
  172. 'id': row[0],
  173. 'name': row[1],
  174. 'target_site': row[2],
  175. 'file_title': row[3],
  176. 'set_name': row[4],
  177. 'serial': row[5],
  178. 'download_state': row[6],
  179. 'image_suffix': row[7],
  180. 'img_url': row[8]
  181. }
  182. )
  183. except psycopg2.Error as e:
  184. print(f"Database error: {e}")
  185. finally:
  186. # 关闭数据库连接
  187. cursor.close()
  188. conn.close()
  189. if load_data_list:
  190. return load_data_list
  191. else:
  192. print("没有需要下载的数据。")
  193. exit(0)
  194. def check_psql():
  195. # 连接数据库
  196. try:
  197. conn = psycopg2.connect(**psql_params)
  198. except Exception as e:
  199. print(f"无法连接到数据库:{e}")
  200. exit(1)
  201. # 创建cursor对象
  202. cur = conn.cursor()
  203. cur.execute("SELECT EXISTS(SELECT FROM pg_catalog.pg_tables WHERE schemaname = 'public' AND tablename = %s)",
  204. (target,))
  205. exist = cur.fetchone()[0]
  206. if not exist:
  207. # 如果不存在,则创建表
  208. cur.execute(f"""
  209. CREATE TABLE {target} (
  210. id SERIAL PRIMARY KEY,
  211. name VARCHAR(255),
  212. target_site VARCHAR(255),
  213. file_title VARCHAR(255),
  214. set_name VARCHAR(255),
  215. serial INT,
  216. download_state BOOLEAN,
  217. image_suffix VARCHAR(50),
  218. img_url VARCHAR(255)
  219. );
  220. """)
  221. print(f"表 '{target}' 创建成功。")
  222. # 提交事务
  223. conn.commit()
  224. # 关闭cursor和连接
  225. cur.close()
  226. conn.close()
  227. def check_local_downloads_dir():
  228. # 查看一下是否存在 downloads 文件夹, 不存在就创建一个
  229. download_file_path = os.path.join(str(project_root), 'downloads')
  230. if not os.path.exists(download_file_path):
  231. os.mkdir(download_file_path)
  232. target_file_path = os.path.join(download_file_path, target)
  233. if not os.path.exists(target_file_path):
  234. os.mkdir(target_file_path)
  235. return target_file_path
  236. def clean_string(string):
  237. string = string.replace('Kaizty Photos: ', '')
  238. string = string.split('|')[0]
  239. string = re.sub(r'[^\u4e00-\u9fff a-zA-Z0-9]', '', string)
  240. string = string.replace(' ', '_')
  241. if string.endswith('_'):
  242. string = string[:-1]
  243. return string
  244. if __name__ == "__main__":
  245. # 检查数据库
  246. check_psql()
  247. txt_file_name = 'target_link.txt'
  248. if not os.path.exists(txt_file_name):
  249. with open(txt_file_name, 'w') as file:
  250. file.write('')
  251. print('需要在 target_link.txt 中填写目标链接')
  252. exit(0)
  253. else:
  254. with open('target_link.txt', 'r') as f:
  255. targets = [target.strip() for target in f.readlines()]
  256. if not targets:
  257. print('在 target_link.txt 中未找到目标链接')
  258. exit(0)
  259. print(f'目标链接是:{targets}')
  260. if step == 1:
  261. all_data = open_browser(targets)
  262. save_data(all_data)
  263. elif step == 2:
  264. # 开始读取数据
  265. load_data = load_data()
  266. # 开始下载 img
  267. target_file_path = check_local_downloads_dir()
  268. download_img(load_data, target_file_path)
  269. print('下载完成, 程序退出')
  270. elif step == 3:
  271. # 保存 img 链接
  272. all_data = open_browser(targets)
  273. save_data(all_data)
  274. # 开始读取数据
  275. load_data = load_data()
  276. # 开始下载 img
  277. target_file_path = check_local_downloads_dir()
  278. download_img(load_data, target_file_path)
  279. print('下载完成, 程序退出')
  280. elif step == 4:
  281. # 调试
  282. all_data = open_browser(targets)
  283. else:
  284. pass