step1.py 6.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193
  1. #!/usr/bin/env python3
  2. # -*- coding: utf-8 -*-
  3. """
  4. 异步批量抓取 E-H 画廊图片链接,按专辑保存 json
  5. python eh_crawler.py
  6. """
  7. from __future__ import annotations
  8. import asyncio
  9. import json
  10. import logging
  11. import re
  12. import sys
  13. from pathlib import Path
  14. from typing import Dict, List, Optional, Tuple
  15. import aiofiles
  16. import httpx
  17. from bs4 import BeautifulSoup
  18. from tqdm.asyncio import tqdm_asyncio
  19. from aiopath import AsyncPath
  20. # -------------------- 可配置常量 --------------------
  21. CONCURRENCY = 20 # 并发页数
  22. MAX_PAGE = 100 # 单专辑最大翻页
  23. RETRY_PER_PAGE = 5 # 单页重试
  24. TIMEOUT = httpx.Timeout(10.0) # 请求超时
  25. IMG_SELECTOR = "#gdt" # 图片入口区域
  26. FAILED_RECORD = "failed_keys.json"
  27. LOG_LEVEL = logging.INFO
  28. # ----------------------------------------------------
  29. logging.basicConfig(
  30. level=LOG_LEVEL,
  31. format="[%(asctime)s] [%(levelname)s] %(message)s",
  32. handlers=[
  33. logging.StreamHandler(sys.stdout),
  34. logging.FileHandler("crawl.log", encoding="utf-8"),
  35. ],
  36. )
  37. log = logging.getLogger("eh_crawler")
  38. # 预编译正则
  39. ILLEGAL_CHARS = re.compile(r'[<>:"/\\|?*\x00-\x1F]')
  40. # -------------------- 工具函数 --------------------
  41. def clean_folder_name(title: str) -> str:
  42. """清洗文件夹名"""
  43. return ILLEGAL_CHARS.sub("_", title).replace(" ", "").replace("_", "").strip() or "gallery"
  44. def load_targets() -> List[str]:
  45. """读取 targets.txt"""
  46. tgt = Path("data/targets.txt")
  47. if not tgt.exists():
  48. log.error("targets.txt 不存在,已自动创建,请先填写 URL")
  49. tgt.touch()
  50. sys.exit(0)
  51. lines = [ln.strip() for ln in tgt.read_text(encoding="utf-8").splitlines() if ln.strip()]
  52. if not lines:
  53. log.error("targets.txt 为空,请先填写 URL")
  54. sys.exit(0)
  55. return list(set(lines)) # 去重
  56. def load_failed() -> List[str]:
  57. if Path(FAILED_RECORD).exists():
  58. try:
  59. return json.loads(Path(FAILED_RECORD).read_text(encoding="utf-8"))
  60. except Exception as exc:
  61. log.warning(f"加载失败记录失败 -> {exc}")
  62. return []
  63. def save_failed(keys: List[str]) -> None:
  64. Path(FAILED_RECORD).write_text(json.dumps(keys, ensure_ascii=False, indent=2), encoding="utf-8")
  65. # -------------------- 爬虫核心 --------------------
  66. async def fetch_page(client: httpx.AsyncClient, url: str) -> Optional[str]:
  67. """获取单页 HTML"""
  68. for attempt in range(1, RETRY_PER_PAGE + 1):
  69. try:
  70. resp = await client.get(url)
  71. resp.raise_for_status()
  72. return resp.text
  73. except httpx.HTTPError as exc:
  74. log.error(f"[{attempt}/{RETRY_PER_PAGE}] 请求失败 {url} -> {exc}")
  75. await asyncio.sleep(2 ** attempt)
  76. return None
  77. async def crawl_single_gallery(
  78. client: httpx.AsyncClient, sem: asyncio.Semaphore, gallery_url: str
  79. ) -> bool:
  80. """抓取单个画廊,成功返回 True"""
  81. async with sem:
  82. base_url = gallery_url.rstrip("/")
  83. key = base_url.split("/")[-1] # 用最后一截当 key
  84. json_name = f"{key}.json"
  85. folder_path: Optional[AsyncPath] = None
  86. json_data: Dict[str, str] = {}
  87. img_count = 1
  88. last_page = False
  89. for page in range(MAX_PAGE):
  90. if last_page:
  91. break
  92. url = f"{base_url}?p={page}"
  93. html = await fetch_page(client, url)
  94. if html is None:
  95. continue
  96. soup = BeautifulSoup(html, "lxml")
  97. title = soup.title.string if soup.title else "gallery"
  98. clean_title = clean_folder_name(title)
  99. folder_path = AsyncPath("data/downloads") / clean_title
  100. await folder_path.mkdir(parents=True, exist_ok=True)
  101. # 如果 json 已存在则跳过整个画廊
  102. json_path = folder_path / json_name
  103. if await json_path.exists():
  104. log.info(f"{json_name} 已存在,跳过")
  105. return True
  106. log.info(f"当前页码:{page + 1} {url}")
  107. selected = soup.select_one(IMG_SELECTOR)
  108. if not selected:
  109. log.warning(f"未找到选择器 {IMG_SELECTOR}")
  110. continue
  111. links = re.findall(r'<a href="(.*?)"', selected.prettify())
  112. if not links:
  113. log.info("本页无图片入口,视为最后一页")
  114. last_page = True
  115. continue
  116. for img_entry in links:
  117. if img_entry in json_data.values():
  118. last_page = True
  119. break
  120. json_data[f"{img_count:04d}"] = img_entry
  121. img_count += 1
  122. if json_data:
  123. await json_path.write_text(
  124. json.dumps(json_data, ensure_ascii=False, indent=2), encoding="utf-8"
  125. )
  126. log.info(f"保存成功 -> {json_path} ({len(json_data)} 张)")
  127. return True
  128. else:
  129. log.warning(f"{key} 未解析到任何图片链接")
  130. return False
  131. # -------------------- 主流程 --------------------
  132. async def main(proxy: str | None = None) -> None:
  133. targets = load_targets()
  134. failed = load_failed()
  135. if failed:
  136. log.info(f"优先重试上次失败画廊: {len(failed)} 个")
  137. all_urls = list(set(targets + failed))
  138. print(proxy)
  139. limits = httpx.Limits(max_keepalive_connections=20, max_connections=50)
  140. async with httpx.AsyncClient(
  141. limits=limits, timeout=TIMEOUT, proxies=proxy, verify=True
  142. ) as client:
  143. sem = asyncio.Semaphore(CONCURRENCY)
  144. results = await tqdm_asyncio.gather(
  145. *[crawl_single_gallery(client, sem, u) for u in all_urls],
  146. desc="Galleries",
  147. total=len(all_urls),
  148. )
  149. # 失败持久化
  150. new_failed = [u for u, ok in zip(all_urls, results) if not ok]
  151. if new_failed:
  152. save_failed(new_failed)
  153. log.warning(f"本轮仍有 {len(new_failed)} 个画廊失败,已写入 {FAILED_RECORD}")
  154. else:
  155. Path(FAILED_RECORD).unlink(missing_ok=True)
  156. log.info("全部画廊抓取完成!")
  157. if __name__ == "__main__":
  158. try:
  159. asyncio.run(main())
  160. except KeyboardInterrupt:
  161. log.info("用户中断,抓取结束")