flaticon.py 12 KB

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