flaticon.py 12 KB

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