flaticon.py 12 KB

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