flaticon.py 12 KB

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