hoopi_mall_group_buy_spider.py 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282
  1. # -*- coding: utf-8 -*-
  2. # Author : Charley
  3. # Python : 3.10.8
  4. # Date : 2025/8/11 16:43
  5. import random
  6. import time
  7. import inspect
  8. import requests
  9. import schedule
  10. from loguru import logger
  11. from mysql_pool import MySQLConnectionPool
  12. from tenacity import retry, stop_after_attempt, wait_fixed
  13. # logger.remove()
  14. # logger.add("./logs/{time:YYYYMMDD}.log", encoding='utf-8', rotation="00:00",
  15. # format="[{time:YYYY-MM-DD HH:mm:ss.SSS}] {level} {message}",
  16. # level="DEBUG", retention="7 day")
  17. category = "团购"
  18. max_page = 50
  19. country_name = 'Malaysia'
  20. def after_log(retry_state):
  21. """
  22. retry 回调
  23. :param retry_state: RetryCallState 对象
  24. """
  25. # 检查 args 是否存在且不为空
  26. if retry_state.args and len(retry_state.args) > 0:
  27. log = retry_state.args[0] # 获取传入的 logger
  28. else:
  29. log = logger # 使用全局 logger
  30. if retry_state.outcome.failed:
  31. log.warning(
  32. f"Function '{retry_state.fn.__name__}', Attempt {retry_state.attempt_number} Times")
  33. else:
  34. log.info(f"Function '{retry_state.fn.__name__}', Attempt {retry_state.attempt_number} succeeded")
  35. @retry(stop=stop_after_attempt(5), wait=wait_fixed(1), after=after_log)
  36. def get_single_page(log, page_no):
  37. log.debug(f"{inspect.currentframe().f_code.co_name} Start get single page, page:{page_no}")
  38. headers = {
  39. "User-Agent": "okhttp/4.10.0",
  40. "Accept-Encoding": "gzip",
  41. "Content-Type": "application/json",
  42. # "x-access-token": "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJsb2dpblR5cGUiOiIxIiwiZXhwIjoxNzU1MTkyNDI2LCJ1c2VybmFtZSI6ImNoYXJsZXlfbGVvQDE2My5jb20ifQ.byBS1zj-LyD1mKHrCx9eLy5X2d0QzTO0FwApj2egSVI",
  43. "country": "1",
  44. "lang": "zh",
  45. "platform": "Android",
  46. "content-type": "application/json; charset=UTF-8"
  47. }
  48. url = "https://cp.hoopi.xyz/hoopiserver/hoopi/api/groupBuy/listGroups"
  49. data = {
  50. "sortType": "8",
  51. "pageNo": page_no,
  52. "pageSize": 10
  53. }
  54. response = requests.post(url, headers=headers, json=data)
  55. # print(response.text)
  56. response.raise_for_status()
  57. if response.status_code == 200:
  58. result = response.json()
  59. if result["success"]:
  60. return result["result"]
  61. else:
  62. log.warning(f"result_message: {result['message']}")
  63. else:
  64. log.warning(f" {inspect.currentframe().f_code.co_name} Request failed with status code: {response.status_code}")
  65. return None
  66. def parse_list_items(log, items, sql_pool):
  67. log.info(f"{inspect.currentframe().f_code.co_name} Start parsing items")
  68. if items:
  69. info_list = []
  70. for item in items:
  71. item_id = item.get('id')
  72. data_dict = {
  73. "item_id": item_id,
  74. "category": category,
  75. "country_name": country_name
  76. }
  77. info_list.append(data_dict)
  78. if info_list:
  79. sql_pool.insert_many(table="hoopi_mall_record", data_list=info_list, ignore=True)
  80. else:
  81. log.warning(f" {inspect.currentframe().f_code.co_name} No items found")
  82. def get_mall_sold_list(log, sql_pool):
  83. page = 1
  84. total_items = 0
  85. # while True:
  86. while page <= max_page:
  87. result = get_single_page(log, page)
  88. if result is None:
  89. break
  90. items = result.get("list", [])
  91. if not items:
  92. log.debug("No items found on page %s", page)
  93. break
  94. try:
  95. parse_list_items(log, items, sql_pool)
  96. except Exception as e:
  97. log.error("Error parsing items on page %s: %s", page, e)
  98. total_items += len(items)
  99. pages = result.get("pages")
  100. total = result.get("total")
  101. # 判断条件 1: 根据 pages 判断
  102. if pages is not None and page >= pages:
  103. log.debug("已爬取 %s 页,共 %s 页" % (page, pages))
  104. break
  105. # 判断条件 2: 根据 list 的长度判断
  106. if len(items) < 10: # pageSize 为 10
  107. log.debug("已获取数据量小于10,停止爬取......................")
  108. break
  109. # 判断条件 3: 根据 total 和已获取数据量判断
  110. if total is not None and total_items >= total:
  111. log.debug("已获取数据量已满足要求,停止爬取......................")
  112. break
  113. page += 1
  114. # time.sleep(random.uniform(0.1, 0.5)) # 添加延时,避免频繁请求
  115. def parse_detail(log, item, sql_pool, item_id):
  116. log.debug("开始解析详情页数据........................")
  117. try:
  118. title = item.get('name')
  119. shopId = item.get('shopId')
  120. shopAppUserId = item.get('shopAppUserId')
  121. shopName = item.get('shopName')
  122. infoImgs = item.get('infoImgs') # 详情图片, 多图, 逗号分隔
  123. cardTypeName = item.get('cardTypeName') # 卡类型
  124. explainIntroduce = item.get('explainIntroduce') # 描述
  125. price = item.get('price')
  126. freightPrice = item.get('freightPrice') # 运费
  127. currency = item.get('currency') # 币种
  128. soldCount = item.get('soldCount') # 售出计数
  129. sellOffCount = item.get('sellOffCount') # 抛售计数
  130. status = item.get('status') # 2:售罄
  131. finishTime = item.get('finishTime')
  132. conditionTypeName = item.get('conditionTypeName') # 评级/状况
  133. countryName = item.get('countryName') # 国家
  134. shopSoldCount = item.get('shopSoldCount') # 店铺已售
  135. data_dict = {
  136. 'title': title,
  137. "shop_id": shopId,
  138. 'shop_name': shopName,
  139. 'shop_app_user_id': shopAppUserId,
  140. 'info_imgs': infoImgs,
  141. 'card_type_name': cardTypeName,
  142. 'explain_introduce': explainIntroduce,
  143. 'price': price,
  144. 'freight_price': freightPrice,
  145. 'currency': currency,
  146. 'sold_count': soldCount,
  147. 'sell_off_count': sellOffCount,
  148. 'status': status,
  149. 'finish_time': finishTime,
  150. 'condition_type_name': conditionTypeName,
  151. 'country_name': countryName,
  152. 'shop_sold_count': shopSoldCount,
  153. 'state': 1
  154. }
  155. # print(data_dict)
  156. try:
  157. sql_pool.update_one_or_dict(table='hoopi_mall_record', data=data_dict, condition={'item_id': item_id})
  158. log.success(f"----------------------- 更新成功, item_id: {item_id} -----------------------")
  159. except Exception as e:
  160. log.error(f'解析详情页数据 update_one_or_dict 报错:{e[:500]}')
  161. sql_pool.update_one_or_dict(table="hoopi_mall_record", data={"state": 3}, condition={"item_id": item_id})
  162. except Exception as e:
  163. log.error(f'解析详情页数据error, {e[:500]}')
  164. sql_pool.update_one_or_dict(table="hoopi_mall_record", data={"state": 3}, condition={"item_id": item_id})
  165. @retry(stop=stop_after_attempt(5), wait=wait_fixed(1), after=after_log)
  166. def get_detail(log, item_id, sql_pool):
  167. log.debug(f"开始获取详情页数据, item_id: {item_id}........................")
  168. headers = {
  169. "User-Agent": "okhttp/4.10.0",
  170. "Accept-Encoding": "gzip",
  171. # "x-access-token": "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJsb2dpblR5cGUiOiIxIiwiZXhwIjoxNzU1MTkyNDI2LCJ1c2VybmFtZSI6ImNoYXJsZXlfbGVvQDE2My5jb20ifQ.byBS1zj-LyD1mKHrCx9eLy5X2d0QzTO0FwApj2egSVI",
  172. "country": "1",
  173. "lang": "zh",
  174. "platform": "Android",
  175. "content-length": "0"
  176. }
  177. url = "https://cp.hoopi.xyz/hoopiserver/hoopi/api/goods/getGoodsInfo/1954822331293704194"
  178. # url = f"https://cp.hoopi.xyz/hoopiserver/hoopi/api/goods/getGoodsInfo/{item_id}"
  179. response = requests.post(url, headers=headers)
  180. # print(response.text)
  181. response.raise_for_status()
  182. data = response.json()
  183. if data['code'] == 200:
  184. result = data.get("result", {})
  185. parse_detail(log, result, sql_pool, item_id)
  186. else:
  187. log.error(f"获取详情页数据失败, item_id: {item_id}, msg:{data['message']}")
  188. sql_pool.update_one_or_dict(table="hoopi_mall_record", data={"state": 3}, condition={"item_id": item_id})
  189. @retry(stop=stop_after_attempt(100), wait=wait_fixed(3600), after=after_log)
  190. def hoopi_mall_group_main(log):
  191. """
  192. 主函数
  193. :param log: logger对象
  194. """
  195. log.info(
  196. f'开始运行 {inspect.currentframe().f_code.co_name} 爬虫任务....................................................')
  197. # 配置 MySQL 连接池
  198. sql_pool = MySQLConnectionPool(log=log)
  199. if not sql_pool.check_pool_health():
  200. log.error("数据库连接池异常")
  201. raise RuntimeError("数据库连接池异常")
  202. try:
  203. try:
  204. # 获取已售出商品列表
  205. get_mall_sold_list(log, sql_pool)
  206. # 获取商品详情
  207. sql_ietm_id_list = sql_pool.select_all(f"SELECT item_id FROM hoopi_mall_record WHERE state != 1 AND category = '{category}' AND country_name = '{country_name}'")
  208. sql_ietm_id_list = [item_id[0] for item_id in sql_ietm_id_list]
  209. for item_id in sql_ietm_id_list:
  210. try:
  211. get_detail(log, item_id, sql_pool)
  212. except Exception as e:
  213. log.error(f"Request get_detail error: {e}")
  214. except Exception as e:
  215. log.error(f"Request get_shop_data_list error: {e}")
  216. except Exception as e:
  217. log.error(f'{inspect.currentframe().f_code.co_name} error: {e}')
  218. finally:
  219. log.info(f'爬虫程序 {inspect.currentframe().f_code.co_name} 运行结束,等待下一轮的采集任务............')
  220. # EmailSender().send(subject="【千岛 拍卖 - 爬虫通知】今日任务已完成",
  221. # content="数据采集和处理已全部完成,请查收结果。\n\n ------ 来自 Python 爬虫系统。")
  222. def schedule_task():
  223. """
  224. 爬虫模块 定时任务 的启动文件
  225. """
  226. # 立即运行一次任务
  227. # hoopi_mall_group_main(log=logger)
  228. # 设置定时任务
  229. schedule.every().day.at("01:06").do(hoopi_mall_group_main, log=logger)
  230. while True:
  231. schedule.run_pending()
  232. time.sleep(1)
  233. if __name__ == '__main__':
  234. # get_mall_sold_list(logger, None)
  235. # get_detail(logger, "1954822331293704194", None)
  236. hoopi_mall_group_main(logger)