base_spider.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306
  1. import asyncio
  2. import uuid
  3. from typing import List, Dict, Optional, Any
  4. import aiohttp
  5. from core.models.video_item import VideoItem
  6. from core.utils.helpers import generate_titles
  7. from core.utils.spider_config import SpiderConfig
  8. from core.utils.extractors import safe_extract, extract_fields
  9. from core.utils.log.logger_manager import LoggerManager
  10. from core.utils.template_resolver import resolve_request_body_template
  11. from services.async_mysql_service import AsyncMysqlService
  12. from services.pipeline import PiaoQuanPipeline
  13. from core.base.async_request_client import AsyncRequestClient
  14. from services.async_mq_producer import AsyncMQProducer
  15. class BaseSpider:
  16. """
  17. 通用爬虫基类,支持:
  18. - 依赖请求参数动态替换(cursor 或其它参数)
  19. - 支持单请求和依赖请求的分页抓取
  20. - 统一日志、MQ推送、异常捕获、异步请求
  21. 子类只需根据业务重写少量方法,如 process_video/process_item。
  22. """
  23. def __init__(self, rule_dict: Dict, user_list: List, env: str = "prod"):
  24. self.env = env
  25. self.user_list = user_list
  26. self.rule_dict = rule_dict
  27. self.class_name = self.__class__.__name__.lower()
  28. # 通过小写子类名读取配置
  29. self.platform_config = SpiderConfig.get_platform_config(classname=self.class_name)
  30. if not self.platform_config:
  31. raise ValueError(f"找不到对应配置: {self.class_name}")
  32. self.platform = self.platform_config.platform
  33. self.mode = self.platform_config.mode
  34. self.logger = LoggerManager.get_logger(platform=self.platform, mode=self.mode)
  35. self.aliyun_log = LoggerManager.get_aliyun_logger(platform=self.platform, mode=self.mode)
  36. self.mq_producer = AsyncMQProducer(topic_name="topic_crawler_etl_prod_v2", platform=self.platform, mode=self.mode)
  37. self.method = self.platform_config.method.upper()
  38. self.url = self.platform_config.url
  39. self.headers = self.platform_config.headers or {}
  40. self.request_body_template = self.platform_config.request_body or {}
  41. self.response_parse = self.platform_config.response_parse or {}
  42. self.next_cursor_path = self.response_parse.get("next_cursor")
  43. self.data_path = self.response_parse.get("data_path")
  44. self.field_map = self.response_parse.get("fields", {})
  45. self.loop_times = self.platform_config.loop_times or 100
  46. self.loop_interval = self.platform_config.loop_interval or 5
  47. self.logger.info(f"开始{self.platform}爬取,最大循环次数{self.loop_times},循环间隔{self.loop_interval}s")
  48. self.feishu_sheetid = self.platform_config.feishu_sheetid
  49. self.db_service = AsyncMysqlService(platform=self.platform, mode=self.mode)
  50. self.request_client = AsyncRequestClient(logger=self.logger, aliyun_log=self.aliyun_log)
  51. self.timeout = self.platform_config.request_timeout or 30
  52. self.max_retries = self.platform_config.max_retries or 3
  53. # 当前分页游标,默认空字符串,支持动态替换request_body中任何字段(如cursor)
  54. self.dynamic_params = {key: "" for key in self.request_body_template.keys()}
  55. # 允许子类重写,支持多游标等复杂情况
  56. self.current_cursor = ""
  57. self.download_cnt = 0
  58. self.limit_flag = False
  59. async def run(self):
  60. """ 爬虫主流程 """
  61. await self.before_run()
  62. total_success, total_fail = 0, 0
  63. async with aiohttp.ClientSession(timeout=aiohttp.ClientTimeout(total=self.timeout)) as session:
  64. for loop_index in range(self.loop_times):
  65. if not await self.is_video_count_sufficient():
  66. self.logger.info(f"视频抓取数量已达上限,提前结束")
  67. return
  68. succ, fail = await self.run_single_loop(session)
  69. total_success += succ
  70. total_fail += fail
  71. await self._wait_for_next_loop(loop_index + 1)
  72. self.logger.info(f"爬虫完成 成功:{total_success} 失败:{total_fail}")
  73. async def run_single_loop(self, session) -> (int, int):
  74. """
  75. 单轮请求与处理
  76. """
  77. success_count, fail_count = 0, 0
  78. try:
  79. # 爬取数据
  80. videos = await self.crawl_data(session)
  81. if not videos:
  82. self.logger.info(f"无数据返回,停止本轮")
  83. return success_count, fail_count
  84. for video in videos:
  85. # 依赖接口请求
  86. video_obj = await self.fetch_dependent_data(video)
  87. res = await self.process_and_push_video(video_obj)
  88. if res:
  89. success_count += 1
  90. else:
  91. fail_count += 1
  92. if self.limit_flag:
  93. break
  94. await self.after_run()
  95. except Exception as e:
  96. self.logger.exception(f"运行异常: {e}")
  97. return success_count, fail_count
  98. async def fetch_dependent_data(self, video: Dict) -> Dict:
  99. """
  100. 可在子类重写以实现依赖请求,用返回结果补充原有 video。
  101. 默认不做处理。
  102. """
  103. return video
  104. async def crawl_data(self, session) -> Optional[List[Dict]]:
  105. """
  106. 请求接口,自动渲染动态参数,自动更新游标
  107. 支持单请求和多请求(分页)逻辑。
  108. """
  109. # 动态渲染请求体
  110. # resolved_body = self._render_request_body()
  111. # 发送请求
  112. response = await self.request_client.request(
  113. session=session,
  114. method=self.method,
  115. url=self.url,
  116. headers=self.headers,
  117. json= self.dynamic_params
  118. )
  119. if not response:
  120. self.logger.error(f"响应为空")
  121. return []
  122. # 更新游标(支持动态参数更新)
  123. if self.next_cursor_path:
  124. next_cursor = safe_extract(response, self.next_cursor_path) or ""
  125. self._update_cursor(next_cursor)
  126. # 解析数据列表
  127. data_list = safe_extract(response, self.data_path)
  128. if not data_list:
  129. self.logger.info(f"未获取到有效数据")
  130. return []
  131. return data_list
  132. def _render_request_body(self) -> Dict:
  133. """
  134. 用当前动态参数渲染请求体模板,支持多参数动态替换
  135. """
  136. body = {}
  137. for k, v in self.request_body_template.items():
  138. if isinstance(v, str) and v.startswith("{{") and v.endswith("}}"):
  139. key = v.strip("{} ")
  140. body[k] = self.dynamic_params.get(key, "")
  141. else:
  142. body[k] = v
  143. return body
  144. def _update_cursor(self, cursor_value: str):
  145. """
  146. 更新分页游标并动态参数,方便下一次请求使用
  147. """
  148. self.current_cursor = cursor_value
  149. # 如果配置的游标字段在请求体中,更新动态参数
  150. if "cursor" in self.dynamic_params:
  151. self.dynamic_params["cursor"] = cursor_value
  152. async def process_and_push_video(self, video: Dict[str, Any]) -> bool:
  153. """
  154. 数据处理完整流程(字段映射 -> 校验 -> 推送)
  155. 子类可重写 process_video 或 filter_data 来定制处理和校验逻辑
  156. """
  157. try:
  158. video_obj = await self.process_video(video)
  159. if not video_obj:
  160. return False
  161. if not await self.filter_data(video_obj):
  162. return False
  163. await self.integrated_video_handling(video_obj)
  164. pushed = await self.push_to_etl(video_obj)
  165. # 达到下载上限,停止继续抓取
  166. if self.rule_dict.get("videos_cnt", {}).get("min") and \
  167. self.download_cnt >= self.rule_dict["videos_cnt"]["min"]:
  168. self.limit_flag = True
  169. if pushed:
  170. self.download_cnt += 1
  171. return pushed
  172. except Exception as e:
  173. self.logger.exception(f"视频处理异常: {e}")
  174. return False
  175. async def process_video(self, video: Dict) -> Optional[Dict]:
  176. """
  177. 统一字段抽取及 VideoItem 初始化
  178. 子类可重写或扩展以定制字段映射、过滤等
  179. """
  180. self.logger.debug(f"处理视频数据: {video.get('title', '无标题')}")
  181. publish_user = None
  182. if self.user_list:
  183. import random
  184. publish_user = random.choice(self.user_list)
  185. else:
  186. publish_user = {"uid": "default", "nick_name": "default_user"}
  187. item_kwargs = extract_fields(video, self.field_map, logger=self.logger,aliyun_log=self.aliyun_log)
  188. item_kwargs.update({
  189. "user_id": publish_user.get("uid"),
  190. "user_name": publish_user.get("nick_name"),
  191. "platform": self.platform,
  192. "strategy": self.mode
  193. })
  194. try:
  195. item = VideoItem(**item_kwargs)
  196. video_dict = await item.produce_item()
  197. if not video_dict:
  198. self.logger.warning(f"VideoItem 校验失败")
  199. return None
  200. return video_dict
  201. except Exception as e:
  202. self.logger.error(f"VideoItem 初始化失败: {e}")
  203. return None
  204. async def filter_data(self, video: Dict) -> bool:
  205. """
  206. 数据校验过滤,默认使用 PiaoQuanPipeline
  207. 子类可重写此方法实现自定义过滤
  208. """
  209. pipeline = PiaoQuanPipeline(
  210. platform=self.platform,
  211. mode=self.mode,
  212. rule_dict=self.rule_dict,
  213. env=self.env,
  214. item=video,
  215. trace_id=self.platform + str(uuid.uuid1())
  216. )
  217. return await pipeline.process_item()
  218. async def integrated_video_handling(self, video: Dict) -> None:
  219. """
  220. 钩子函数:可在此实现自动生成标题或其他业务逻辑
  221. """
  222. await generate_titles(self.feishu_sheetid, video)
  223. async def push_to_etl(self, video: Dict) -> bool:
  224. """
  225. 推送消息到消息队列ETL
  226. """
  227. try:
  228. await self.mq_producer.send_msg(video)
  229. self.logger.info(f"成功推送视频至ETL")
  230. return True
  231. except Exception as e:
  232. self.logger.exception(f"推送ETL失败: {e}")
  233. return False
  234. async def is_video_count_sufficient(self) -> bool:
  235. """
  236. 判断当天抓取的视频是否已达到上限,达到则停止继续抓取
  237. """
  238. max_count = self.rule_dict.get("videos_cnt", {}).get("min", 0)
  239. if max_count <= 0:
  240. return True
  241. async with AsyncMysqlService(self.platform, self.mode) as mysql:
  242. current_count = await mysql.get_today_videos()
  243. if current_count >= max_count:
  244. self.logger.info(f"{self.platform} 今日视频数量已达上限: {current_count}")
  245. self.aliyun_log.logging(code="1011", message="视频数量达到当日最大值", data=f"<今日视频数量>{current_count}")
  246. return False
  247. return True
  248. async def _wait_for_next_loop(self, current_loop: int) -> None:
  249. """等待下次循环"""
  250. if current_loop < self.loop_times and self.loop_interval > 0:
  251. self.logger.info(f"等待 {self.loop_interval} 秒后进行下一次请求")
  252. await asyncio.sleep(self.loop_interval)
  253. async def before_run(self):
  254. """运行前预处理钩子,子类可覆盖"""
  255. pass
  256. async def after_run(self):
  257. """运行后处理钩子,子类可覆盖"""
  258. pass