flaticon.py 13 KB

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