flaticon.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353
  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. save_data({title: urls})
  101. # 获取所有 url 数据之后, 存数据库
  102. # return all_data
  103. def download_img(load_data, target_file_path):
  104. # 连接数据库, 准备反写下载状态
  105. conn = psycopg2.connect(**psql_params)
  106. cursor = conn.cursor()
  107. print('正在下载图片')
  108. for data in load_data:
  109. # 如果img文件存在, 即已经下载过, 直接跳过
  110. id = data['id']
  111. name = data['name']
  112. target_site = data['target_site'],
  113. file_title = data['file_title'].replace(' ', '_')
  114. set_name = data['set_name']
  115. serial = str(data['serial']).zfill(3)
  116. image_suffix = data['image_suffix']
  117. img_url = data['img_url']
  118. # 查看每个合集的文件夹是否存在, 不存在就创建
  119. title_file_path = os.path.join(target_file_path, file_title)
  120. if not os.path.exists(title_file_path):
  121. os.mkdir(title_file_path)
  122. img_name = f'{file_title}_{serial}.{image_suffix}' # 图片文件名
  123. img_file_path = os.path.join(str(title_file_path), img_name) # 图片完整路径
  124. if os.path.exists(img_file_path):
  125. # 当此 img 已存在本地时, 在 psql 将数据库状态改为已下载
  126. query = f"UPDATE {target} SET download_state = %s WHERE id = %s"
  127. cursor.execute(query, (True, id))
  128. conn.commit()
  129. print(f'图片 {img_file_path} 已存在。继续!')
  130. continue
  131. retry = 8
  132. while retry:
  133. try:
  134. resp = httpx.get(img_url, headers={
  135. "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"
  136. })
  137. with open(img_file_path, 'wb') as f:
  138. f.write(resp.content)
  139. # 下载成功后, 在 psql 将数据库状态改为已下载
  140. query = f"UPDATE {target} SET download_state = %s WHERE id = %s"
  141. cursor.execute(query, (True, id))
  142. conn.commit()
  143. print(f'已下载:{img_name}')
  144. time.sleep(random.uniform(1, 2))
  145. break
  146. except Exception as e:
  147. print(f'下载图片失败:{img_name}。错误:{e} 重试: {retry}')
  148. retry -= 1
  149. time.sleep(random.uniform(3, 5))
  150. def save_data(data_item):
  151. conn = psycopg2.connect(**psql_params)
  152. cursor = conn.cursor()
  153. for k, v in data_item.items():
  154. for data in v:
  155. # 检查img_url是否重复
  156. cursor.execute("SELECT img_url FROM flaticon WHERE img_url = %s", (data['url'],))
  157. if cursor.fetchone() is None:
  158. # 插入数据
  159. cursor.execute("""
  160. INSERT INTO flaticon (name, target_site, file_title, set_name, serial, download_state, image_suffix, img_url)
  161. VALUES (%s, %s, %s, %s, %s, %s, %s, %s)
  162. """, (
  163. None,
  164. target,
  165. data['file_title'],
  166. None,
  167. data['serial'],
  168. False,
  169. data['suffix'],
  170. data['url']
  171. ))
  172. conn.commit()
  173. print(f"数据 {data['url']} 插入成功")
  174. else:
  175. print(f"数据 {data['url']} 已存在,未插入")
  176. # 关闭数据库连接
  177. cursor.close()
  178. conn.close()
  179. def load_data():
  180. # 连接数据库
  181. conn = psycopg2.connect(**psql_params)
  182. cursor = conn.cursor()
  183. # 查询download_state为false的所有数据
  184. query = f"SELECT * FROM {target} WHERE download_state = %s order by id asc"
  185. load_data_list = []
  186. try:
  187. # 执行查询
  188. cursor.execute(query, (False,))
  189. # 获取查询结果
  190. rows = cursor.fetchall()
  191. # 打印结果
  192. for row in rows:
  193. load_data_list.append(
  194. {
  195. 'id': row[0],
  196. 'name': row[1],
  197. 'target_site': row[2],
  198. 'file_title': row[3],
  199. 'set_name': row[4],
  200. 'serial': row[5],
  201. 'download_state': row[6],
  202. 'image_suffix': row[7],
  203. 'img_url': row[8]
  204. }
  205. )
  206. except psycopg2.Error as e:
  207. print(f"Database error: {e}")
  208. finally:
  209. # 关闭数据库连接
  210. cursor.close()
  211. conn.close()
  212. if load_data_list:
  213. return load_data_list
  214. else:
  215. print("没有需要下载的数据。")
  216. exit(0)
  217. def check_psql():
  218. # 连接数据库
  219. try:
  220. conn = psycopg2.connect(**psql_params)
  221. except Exception as e:
  222. print(f"无法连接到数据库:{e}")
  223. exit(1)
  224. # 创建cursor对象
  225. cur = conn.cursor()
  226. cur.execute("SELECT EXISTS(SELECT FROM pg_catalog.pg_tables WHERE schemaname = 'public' AND tablename = %s)",
  227. (target,))
  228. exist = cur.fetchone()[0]
  229. if not exist:
  230. # 如果不存在,则创建表
  231. cur.execute(f"""
  232. CREATE TABLE {target} (
  233. id SERIAL PRIMARY KEY,
  234. name VARCHAR(255),
  235. target_site VARCHAR(255),
  236. file_title VARCHAR(255),
  237. set_name VARCHAR(255),
  238. serial INT,
  239. download_state BOOLEAN,
  240. image_suffix VARCHAR(50),
  241. img_url VARCHAR(255)
  242. );
  243. """)
  244. print(f"表 '{target}' 创建成功。")
  245. # 提交事务
  246. conn.commit()
  247. # 关闭cursor和连接
  248. cur.close()
  249. conn.close()
  250. def check_local_downloads_dir():
  251. # 查看一下是否存在 downloads 文件夹, 不存在就创建一个
  252. download_file_path = os.path.join(str(project_root), 'downloads')
  253. if not os.path.exists(download_file_path):
  254. os.mkdir(download_file_path)
  255. target_file_path = os.path.join(download_file_path, target)
  256. if not os.path.exists(target_file_path):
  257. os.mkdir(target_file_path)
  258. return target_file_path
  259. if __name__ == "__main__":
  260. # 检查数据库
  261. check_psql()
  262. txt_file_name = 'target_link.txt'
  263. if not os.path.exists(txt_file_name):
  264. with open(txt_file_name, 'w') as file:
  265. file.write('')
  266. print('需要在 target_link.txt 中填写目标链接')
  267. exit(0)
  268. else:
  269. with open('target_link.txt', 'r') as f:
  270. targets = [target.strip() for target in f.readlines()]
  271. if not targets:
  272. print('在 target_link.txt 中未找到目标链接')
  273. exit(0)
  274. print(f'目标链接是:{targets}')
  275. if step == 1:
  276. open_browser(targets)
  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. open_browser(targets)
  287. # 开始读取数据
  288. load_data = load_data()
  289. # 开始下载 img
  290. target_file_path = check_local_downloads_dir()
  291. download_img(load_data, target_file_path)
  292. print('下载完成, 程序退出')
  293. elif step == 4:
  294. # 调试
  295. pass
  296. else:
  297. pass