in_auction_general_spider.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357
  1. # -*- coding: utf-8 -*-
  2. # Author : Charley
  3. # Python : 3.10.8
  4. # Date : 2025/9/12 16:27
  5. import inspect
  6. import requests
  7. from loguru import logger
  8. from mysql_pool import MySQLConnectionPool
  9. from tenacity import retry, stop_after_attempt, wait_fixed
  10. logger.remove()
  11. logger.add("./logs/{time:YYYYMMDD}.log", encoding='utf-8', rotation="00:00",
  12. format="[{time:YYYY-MM-DD HH:mm:ss.SSS}] {level} {message}",
  13. level="DEBUG", retention="7 day")
  14. category = "general"
  15. max_page = 50
  16. country_name = 'Indonesia'
  17. headers = {
  18. "User-Agent": "okhttp/4.10.0",
  19. "Accept-Encoding": "gzip",
  20. "Content-Type": "application/json",
  21. # "x-access-token": "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJsb2dpblR5cGUiOiIxIiwiZXhwIjoxNzU3OTUwODI0LCJ1c2VybmFtZSI6InRpYW56aHUxMDA5QGdtYWlsLmNvbSJ9.PkSn4I2evvlF27OfrxGidT-IwuuTo9nNDukuHSHSs0w",
  22. "country": "1875086144853712897",
  23. "lang": "zh",
  24. "platform": "Android",
  25. "content-type": "application/json; charset=UTF-8"
  26. }
  27. def after_log(retry_state):
  28. """
  29. retry 回调
  30. :param retry_state: RetryCallState 对象
  31. """
  32. # 检查 args 是否存在且不为空
  33. if retry_state.args and len(retry_state.args) > 0:
  34. log = retry_state.args[0] # 获取传入的 logger
  35. else:
  36. log = logger # 使用全局 logger
  37. if retry_state.outcome.failed:
  38. log.warning(
  39. f"Function '{retry_state.fn.__name__}', Attempt {retry_state.attempt_number} Times")
  40. else:
  41. log.info(f"Function '{retry_state.fn.__name__}', Attempt {retry_state.attempt_number} succeeded")
  42. @retry(stop=stop_after_attempt(5), wait=wait_fixed(1), after=after_log)
  43. def get_general_single_page(log, page_no):
  44. url = "https://cp.hoopi.xyz/hoopiserver/hoopi/api/goods/listGoods"
  45. data = {
  46. "sortType": "2",
  47. "containType": [
  48. "2"
  49. ],
  50. # "pageNo": 1,
  51. "pageNo": page_no,
  52. "premierGoods": "0",
  53. "pageSize": 15,
  54. "isSellOutShow": "1",
  55. "status": "2"
  56. }
  57. response = requests.post(url, headers=headers, json=data, timeout=22)
  58. # print(response.text)
  59. response.raise_for_status()
  60. if response.status_code == 200:
  61. result = response.json()
  62. if result["success"]:
  63. return result["result"]
  64. else:
  65. log.warning(f"result_message: {result['message']}")
  66. else:
  67. log.warning(f" {inspect.currentframe().f_code.co_name} Request failed with status code: {response.status_code}")
  68. return None
  69. def parse_list_items(log, items, sql_pool):
  70. log.info(f"{inspect.currentframe().f_code.co_name} Start parsing items")
  71. if items:
  72. info_list = []
  73. for item in items:
  74. item_id = item.get('id')
  75. data_dict = {
  76. "item_id": item_id,
  77. "category": category,
  78. "country_name": country_name
  79. }
  80. info_list.append(data_dict)
  81. if info_list:
  82. sql_pool.insert_many(table="hoopi_auction_record", data_list=info_list, ignore=True)
  83. else:
  84. log.warning(f" {inspect.currentframe().f_code.co_name} No items found")
  85. def get_general_list(log, sql_pool):
  86. page = 1
  87. total_items = 0
  88. # while True:
  89. while page <= max_page:
  90. result = get_general_single_page(log, page)
  91. if result is None:
  92. break
  93. items = result.get("list", [])
  94. if not items:
  95. log.debug("No items found on page %s", page)
  96. break
  97. try:
  98. parse_list_items(log, items, sql_pool)
  99. except Exception as e:
  100. log.error("Error parsing items on page %s: %s", page, e)
  101. total_items += len(items)
  102. pages = result.get("pages")
  103. total = result.get("total")
  104. # 判断条件 1: 根据 pages 判断
  105. if pages is not None and page >= pages:
  106. log.debug("已爬取 %s 页,共 %s 页" % (page, pages))
  107. break
  108. # 判断条件 2: 根据 list 的长度判断
  109. if len(items) < 15: # pageSize 为 15
  110. log.debug("已获取数据量小于15,停止爬取......................")
  111. break
  112. # 判断条件 3: 根据 total 和已获取数据量判断
  113. if total is not None and total_items >= total:
  114. log.debug("已获取数据量已满足要求,停止爬取......................")
  115. break
  116. page += 1
  117. # time.sleep(random.uniform(0.1, 0.5)) # 添加延时,避免频繁请求
  118. # ----------------------------------------------------------------------------------------------------------------------
  119. def parse_detail(log, item, sql_pool, item_id):
  120. log.debug("开始解析详情页数据........................")
  121. try:
  122. title = item.get('name')
  123. shopId = item.get('shopId')
  124. shopAppUserId = item.get('shopAppUserId')
  125. shopName = item.get('shopName')
  126. infoImgs = item.get('infoImgs') # 详情图片, 多图, 逗号分隔
  127. cardTypeName = item.get('cardTypeName') # 卡类型
  128. explainIntroduce = item.get('explainIntroduce') # 描述
  129. # 去除表情符号
  130. # if explainIntroduce:
  131. # explainIntroduce = emoji.replace_emoji(explainIntroduce, replace='')
  132. price = item.get('price')
  133. freightPrice = item.get('freightPrice') # 运费
  134. currency = item.get('currency') # 币种
  135. soldCount = item.get('soldCount') # 售出计数
  136. sellOffCount = item.get('sellOffCount') # 抛售计数
  137. status = item.get('status') # 2:售罄
  138. finishTime = item.get('finishTime')
  139. conditionTypeName = item.get('conditionTypeName') # 评级/状况
  140. countryName = item.get('countryName') # 国家
  141. if not countryName:
  142. countryName = country_name
  143. shopSoldCount = item.get('shopSoldCount') # 店铺已售
  144. bidCount = item.get('bidCount') # 竞拍次数
  145. data_dict = {
  146. 'title': title,
  147. "shop_id": shopId,
  148. 'shop_name': shopName,
  149. 'shop_app_user_id': shopAppUserId,
  150. 'info_imgs': infoImgs,
  151. 'card_type_name': cardTypeName,
  152. 'explain_introduce': explainIntroduce,
  153. 'price': price,
  154. 'freight_price': freightPrice,
  155. 'currency': currency,
  156. 'sold_count': soldCount,
  157. 'sell_off_count': sellOffCount,
  158. 'status': status,
  159. 'finish_time': finishTime,
  160. 'condition_type_name': conditionTypeName,
  161. 'country_name': countryName,
  162. 'shop_sold_count': shopSoldCount,
  163. 'bid_count': bidCount,
  164. 'state': 1
  165. }
  166. # print('data_dict:',data_dict)
  167. try:
  168. sql_pool.update_one_or_dict(table='hoopi_auction_record', data=data_dict, condition={'item_id': item_id})
  169. log.success(f"----------------------- 更新成功, item_id: {item_id} -----------------------")
  170. except Exception as e:
  171. log.error(f'解析详情页数据 update_one_or_dict 报错:{e}')
  172. sql_pool.update_one_or_dict(table="hoopi_auction_record", data={"state": 3}, condition={"item_id": item_id})
  173. except Exception as e:
  174. log.error(f'解析详情页数据error, {e}')
  175. sql_pool.update_one_or_dict(table="hoopi_auction_record", data={"state": 3}, condition={"item_id": item_id})
  176. @retry(stop=stop_after_attempt(5), wait=wait_fixed(1), after=after_log)
  177. def get_detail(log, item_id, sql_pool):
  178. log.debug(f"开始获取详情页数据, item_id: {item_id}........................")
  179. # url = "https://cp.hoopi.xyz/hoopiserver/hoopi/api/goods/getGoodsInfo/1954822331293704194"
  180. url = f"https://cp.hoopi.xyz/hoopiserver/hoopi/api/goods/getGoodsInfo/{item_id}"
  181. response = requests.post(url, headers=headers, timeout=10)
  182. # print(response.text)
  183. response.raise_for_status()
  184. data = response.json()
  185. if data['code'] == 200:
  186. result = data.get("result", {})
  187. parse_detail(log, result, sql_pool, item_id)
  188. else:
  189. log.error(f"获取详情页数据失败, item_id: {item_id}, msg:{data['message']}")
  190. sql_pool.update_one_or_dict(table="hoopi_auction_record", data={"state": 3}, condition={"item_id": item_id})
  191. # -------------------------------------------------------------------------------------------------------------------
  192. @retry(stop=stop_after_attempt(5), wait=wait_fixed(1), after=after_log)
  193. def get_bid_list(log, item_id, sql_pool, token):
  194. log.debug(f"开始获取竞拍记录数据, item_id: {item_id}........................")
  195. headers_bid = {
  196. # "x-access-token": "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJsb2dpblR5cGUiOiIxIiwiZXhwIjoxNzU3OTUwODI0LCJ1c2VybmFtZSI6InRpYW56aHUxMDA5QGdtYWlsLmNvbSJ9.PkSn4I2evvlF27OfrxGidT-IwuuTo9nNDukuHSHSs0w"
  197. "x-access-token": token
  198. }
  199. copy_headers = headers.copy()
  200. copy_headers.update(headers_bid)
  201. # print(copy_headers)
  202. # url = "https://cp.hoopi.xyz/hoopiserver/hoopi/api/goodsAuction/getBidRecordByGoodsId/1830661503251054593"
  203. url = f"https://cp.hoopi.xyz/hoopiserver/hoopi/api/goodsAuction/getBidRecordByGoodsId/{item_id}"
  204. response = requests.post(url, headers=copy_headers)
  205. # print(response.text)
  206. response.raise_for_status()
  207. if response.status_code == 200:
  208. biddings = response.json()["result"]
  209. """
  210. 获取 biddings 信息
  211. """
  212. # biddings = resp_json.get('biddings', [])
  213. # print(biddings)
  214. # 创建一个字典来存储每个用户的最高出价记录
  215. highest_bids = {}
  216. for record in biddings:
  217. username = record['appUserName']
  218. bid_price = float(record['bidPrice']) # 将出价转换为浮点数以便比较
  219. # 如果用户不在字典中,或者当前出价高于已存储的最高出价,则更新记录
  220. if username not in highest_bids or bid_price > float(highest_bids[username]['bidPrice']):
  221. highest_bids[username] = record
  222. bids_list = list(highest_bids.values())
  223. # print(highest_bids)
  224. # print(bids_list)
  225. biddings_list = [
  226. {
  227. 'item_id': item_id,
  228. 'bid_id': record['id'],
  229. 'user_id': record['appUserId'],
  230. 'username': record['appUserName'],
  231. 'bid_price': record['bidPrice'],
  232. 'bid_time': record['bidTime'],
  233. }
  234. for record in bids_list
  235. ]
  236. # print('biddings_list:', biddings_list)
  237. if biddings_list:
  238. sql_pool.insert_many(table='hoopi_auction_bid_record', data_list=biddings_list)
  239. sql_pool.update_one_or_dict(table="hoopi_auction_record", data={"bid_state": 1},
  240. condition={"item_id": item_id})
  241. log.success(f"----------------------- 添加成功, item_id: {item_id} -----------------------")
  242. else:
  243. log.warning(f"----------------------- 添加失败, item_id: {item_id} -----------------------")
  244. sql_pool.update_one_or_dict(table="hoopi_auction_record", data={"bid_state": 2},
  245. condition={"item_id": item_id})
  246. else:
  247. log.warning(f" {inspect.currentframe().f_code.co_name} Request failed with status code: {response.status_code}")
  248. sql_pool.update_one_or_dict(table="hoopi_auction_record", data={"bid_state": 3}, condition={"item_id": item_id})
  249. @retry(stop=stop_after_attempt(100), wait=wait_fixed(3600), after=after_log)
  250. def in_general_main(log):
  251. """
  252. 主函数
  253. :param log: logger对象
  254. """
  255. log.info(
  256. f'开始运行 {inspect.currentframe().f_code.co_name} 爬虫任务....................................................')
  257. # 配置 MySQL 连接池
  258. sql_pool = MySQLConnectionPool(log=log)
  259. if not sql_pool.check_pool_health():
  260. log.error("数据库连接池异常")
  261. raise RuntimeError("数据库连接池异常")
  262. try:
  263. try:
  264. # 获取已售出商品列表
  265. log.debug(f"开始获取已售出商品列表, category: {category}........................")
  266. get_general_list(log, sql_pool)
  267. # 获取商品详情
  268. log.debug(f"开始获取商品详情, category: {category}........................")
  269. sql_ietm_id_list = sql_pool.select_all(
  270. f"SELECT item_id FROM hoopi_auction_record WHERE state != 1 AND category = '{category}' AND country_name = '{country_name}'")
  271. sql_ietm_id_list = [item_id[0] for item_id in sql_ietm_id_list]
  272. for item_id in sql_ietm_id_list:
  273. try:
  274. get_detail(log, item_id, sql_pool)
  275. except Exception as e:
  276. log.error(f"Request get_detail error: {e}")
  277. # 获取商品出价列表
  278. log.debug(f"开始获取商品出价列表, category: {category}........................")
  279. # 获取 token
  280. token = sql_pool.select_one("SELECT token FROM hoopi_token")
  281. token = token[0]
  282. sql_bid_state_list = sql_pool.select_all(
  283. f"SELECT item_id FROM hoopi_auction_record WHERE bid_state != 1 AND category = '{category}' AND country_name = '{country_name}'")
  284. sql_bid_state_list = [item_id[0] for item_id in sql_bid_state_list]
  285. for item_id in sql_bid_state_list:
  286. try:
  287. get_bid_list(log, item_id, sql_pool, token)
  288. except Exception as e:
  289. log.error(f"Request get_bid_list error: {e}")
  290. except Exception as e:
  291. log.error(f"Request get_shop_data_list error: {e}")
  292. except Exception as e:
  293. log.error(f'{inspect.currentframe().f_code.co_name} error: {e}')
  294. finally:
  295. log.info(f'爬虫程序 {inspect.currentframe().f_code.co_name} 运行结束,等待下一轮的采集任务............')
  296. # EmailSender().send(subject="【千岛 拍卖 - 爬虫通知】今日任务已完成",
  297. # content="数据采集和处理已全部完成,请查收结果。\n\n ------ 来自 Python 爬虫系统。")
  298. if __name__ == '__main__':
  299. # get_general_list(logger, None)
  300. # get_bid_list(logger, '1830661503251054593', None)
  301. in_general_main(logger)