hoopi_mall_card_spider.py 11 KB

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