flaticon.py 12 KB

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