jhs_new_daily_spider.py 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324
  1. # -*- coding: utf-8 -*-
  2. # Author : Charley
  3. # Python : 3.10.8
  4. # Date : 2025/3/19 18:55
  5. import time
  6. import inspect
  7. import requests
  8. import schedule
  9. import user_agent
  10. from loguru import logger
  11. from datetime import datetime
  12. from mysq_pool import MySQLConnectionPool
  13. from tenacity import retry, stop_after_attempt, wait_fixed
  14. """
  15. com.jihuanshe
  16. """
  17. logger.remove()
  18. logger.add("./logs/{time:YYYYMMDD}.log", encoding='utf-8', rotation="00:00",
  19. format="[{time:YYYY-MM-DD HH:mm:ss.SSS}] {level} {message}",
  20. level="DEBUG", retention="7 day")
  21. def after_log(retry_state):
  22. """
  23. retry 回调
  24. :param retry_state: RetryCallState 对象
  25. """
  26. # 检查 args 是否存在且不为空
  27. if retry_state.args and len(retry_state.args) > 0:
  28. log = retry_state.args[0] # 获取传入的 logger
  29. else:
  30. log = logger # 使用全局 logger
  31. if retry_state.outcome.failed:
  32. log.warning(
  33. f"Function '{retry_state.fn.__name__}', Attempt {retry_state.attempt_number} Times")
  34. else:
  35. log.info(f"Function '{retry_state.fn.__name__}', Attempt {retry_state.attempt_number} succeeded")
  36. @retry(stop=stop_after_attempt(5), wait=wait_fixed(1), after=after_log)
  37. def get_proxys(log):
  38. """
  39. 获取代理
  40. :return: 代理
  41. """
  42. tunnel = "x371.kdltps.com:15818"
  43. kdl_username = "t13753103189895"
  44. kdl_password = "o0yefv6z"
  45. try:
  46. proxies = {
  47. "http": "http://%(user)s:%(pwd)s@%(proxy)s/" % {"user": kdl_username, "pwd": kdl_password, "proxy": tunnel},
  48. "https": "http://%(user)s:%(pwd)s@%(proxy)s/" % {"user": kdl_username, "pwd": kdl_password, "proxy": tunnel}
  49. }
  50. return proxies
  51. except Exception as e:
  52. log.error(f"Error getting proxy: {e}")
  53. raise e
  54. def save_product_data(sql_pool, product_info: tuple):
  55. """
  56. 保存 product 数据
  57. :param sql_pool: MySQL连接池对象
  58. :param product_info: 要保存的数据
  59. """
  60. sql = """
  61. INSERT INTO jhs_product_record (seller_user_id, seller_username, product_id, app_id, nonce_str, signature, auction_product_name, auction_product_images, game_key, language_text, authenticator_name, grading, starting_price, max_bid_price, status, auction_product_start_time, auction_product_end_time)
  62. VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s)"""
  63. sql_pool.insert_one(sql, product_info)
  64. def save_biddings_data(sql_pool, biddings_list: list):
  65. """
  66. 保存 biddings 数据
  67. :param sql_pool: MySQL连接池对象
  68. :param biddings_list: 要保存的数据 -> list
  69. """
  70. sql = """
  71. INSERT INTO jhs_biddings_record (product_id, username, bid_price, bid_status, created_at)
  72. VALUES (%s, %s, %s, %s, %s)"""
  73. sql_pool.insert_all(sql, biddings_list)
  74. def save_shop_data(sql_pool, shop_info: tuple):
  75. """
  76. 保存 product 数据
  77. :param sql_pool: MySQL连接池对象
  78. :param shop_info: 要保存的数据
  79. """
  80. sql = """
  81. INSERT INTO jhs_shop_record (seller_user_id, seller_username, follower_count, success_order_user_count, seller_credit_rank_image_url)
  82. VALUES (%s, %s, %s, %s, %s)"""
  83. sql_pool.insert_one(sql, shop_info)
  84. def parse_data(log, resp_json, sql_product_id, sql_pool, sql_shop_id_list):
  85. """
  86. 解析数据, 将解析后的数据, 分成三个表存储 product
  87. biddings
  88. shop
  89. :param log: logger对象
  90. :param resp_json: resp_json
  91. :param sql_product_id: sql_product_id
  92. :param sql_pool: MySQL连接池对象
  93. :param sql_shop_id_list: sql_shop_id_list
  94. """
  95. sql_id = sql_product_id[0]
  96. pid = sql_product_id[1]
  97. status = resp_json.get('status')
  98. if status not in ['ongoing', 'pending']:
  99. """
  100. 获取 shop 信息
  101. """
  102. seller_user_id = resp_json.get('seller_user_id')
  103. seller_username = resp_json.get('seller_username')
  104. # print(seller_user_id)
  105. # # 查询商家id在不在数据库中
  106. # sql_exists_flag = """SELECT EXISTS (SELECT 1 FROM jhs_shop_record WHERE seller_user_id = %s) AS exists_flag"""
  107. # exists_flag = sql_pool.select_one(sql_exists_flag, (seller_user_id,))
  108. # exists_flag = exists_flag[0]
  109. # if exists_flag == 1:
  110. if str(seller_user_id) in sql_shop_id_list:
  111. log.info(
  112. f"----------------- The seller_user_id {seller_user_id} is already in the database, Not need save -----------------")
  113. else:
  114. follower_count = resp_json.get('follower_count')
  115. success_order_user_count = resp_json.get('success_order_user_count')
  116. seller_credit_rank_image_url = resp_json.get('seller_credit_rank_image_url')
  117. shop_info = (
  118. seller_user_id, seller_username, follower_count, success_order_user_count, seller_credit_rank_image_url
  119. )
  120. # print(shop_info)
  121. try:
  122. save_shop_data(sql_pool, shop_info)
  123. sql_shop_id_list.append(seller_user_id)
  124. except Exception as e:
  125. if "Duplicate entry" in str(e):
  126. logger.warning(f"存在重复的 seller_user_id{seller_user_id},跳过插入....")
  127. else:
  128. logger.error(f"保存数据 seller_user_id 时出错: {str(e)}")
  129. # sql_pool.update_one("update jhs_task set task_state = 1 where id = %s", (sql_id,))
  130. """
  131. 获取 product 信息
  132. """
  133. app_id = resp_json.get('appId')
  134. nonce_str = resp_json.get('nonceStr')
  135. signature = resp_json.get('signature')
  136. # auction_product_id = resp_json.get('auction_product_id')
  137. auction_product_name = resp_json.get('auction_product_name')
  138. auction_product_images_list = resp_json.get('auction_product_images', [])
  139. if auction_product_images_list:
  140. auction_product_images = ','.join(auction_product_images_list)
  141. else:
  142. auction_product_images = None
  143. game_key = resp_json.get('game_key')
  144. language_text = resp_json.get('language_text')
  145. authenticator_name = resp_json.get('authenticator_name')
  146. grading = resp_json.get('grading')
  147. starting_price = resp_json.get('starting_price')
  148. max_bid_price = resp_json.get('max_bid_price')
  149. auction_product_start_timestamp = resp_json.get('auction_product_start_timestamp')
  150. auction_product_start_time = datetime.fromtimestamp(auction_product_start_timestamp).strftime(
  151. '%Y-%m-%d %H:%M:%S') if auction_product_start_timestamp else None
  152. auction_product_end_timestamp = resp_json.get('auction_product_end_timestamp')
  153. auction_product_end_time = datetime.fromtimestamp(auction_product_end_timestamp).strftime(
  154. '%Y-%m-%d %H:%M:%S') if auction_product_end_timestamp else None
  155. product_info = (
  156. seller_user_id, seller_username, pid, app_id, nonce_str, signature, auction_product_name,
  157. auction_product_images, game_key, language_text, authenticator_name, grading, starting_price, max_bid_price,
  158. status, auction_product_start_time, auction_product_end_time
  159. )
  160. # print(product_info)
  161. try:
  162. save_product_data(sql_pool, product_info)
  163. sql_pool.update_one("update jhs_task set task_state = 1 where id = %s", (sql_id,))
  164. except Exception as e:
  165. if "Duplicate entry" in str(e):
  166. logger.warning(f"存在重复的 pid{pid},跳过插入....")
  167. else:
  168. logger.error(f"保存数据时出错: {str(e)}")
  169. return
  170. """
  171. 获取 biddings 信息
  172. """
  173. biddings = resp_json.get('biddings', [])
  174. # print(biddings)
  175. # 创建一个字典来存储每个用户的最高出价记录
  176. highest_bids = {}
  177. for record in biddings:
  178. username = record['username']
  179. bid_price = float(record['bid_price']) # 将出价转换为浮点数以便比较
  180. # 如果用户不在字典中,或者当前出价高于已存储的最高出价,则更新记录
  181. if username not in highest_bids or bid_price > float(highest_bids[username]['bid_price']):
  182. highest_bids[username] = record
  183. bids_list = list(highest_bids.values())
  184. biddings_list = [
  185. (pid, record['username'], record['bid_price'], record['bid_status'], record['created_at'])
  186. for record in bids_list
  187. ]
  188. # print(biddings_list)
  189. if biddings_list:
  190. save_biddings_data(sql_pool, biddings_list)
  191. else:
  192. log.info(f"................ No biddings found for product {pid}, Not need save ................")
  193. else:
  194. log.info(f"................ The product {pid} is ongoing or pending, Not need parse ................")
  195. sql_pool.update_one("update jhs_task set task_state = 4 where id = %s", (sql_id,))
  196. @retry(stop=stop_after_attempt(5), wait=wait_fixed(1), after=after_log)
  197. def get_resp(log, sql_product_id, sql_pool, sql_shop_id_list):
  198. """
  199. 获取 response 响应
  200. :param log: logger对象
  201. :param sql_product_id: sql_product_id
  202. :param sql_pool: MySQL连接池对象
  203. :param sql_shop_id_list: sql_shop_id_list
  204. """
  205. sql_id = sql_product_id[0]
  206. pid = sql_product_id[1]
  207. headers = {
  208. "accept": "application/json, text/plain, */*",
  209. "referer": "https://www.jihuanshe.com/",
  210. "user-agent": user_agent.generate_user_agent()
  211. }
  212. url = "https://api.jihuanshe.com/api/market/share/auction-product"
  213. params = {
  214. "auction_product_id": pid,
  215. "url": f"https://www.jihuanshe.com/app/auction?auctionProductId={pid}"
  216. }
  217. response = requests.get(url, headers=headers, params=params, timeout=5, proxies=get_proxys(log))
  218. # print(response.json())
  219. # print(response)
  220. resp_json = response.json()
  221. if resp_json:
  222. if resp_json.get("code") == 440:
  223. log.debug(f"< 抱歉,该竞价商品已被移除, pid:{pid} >")
  224. sql_pool.update_one("update jhs_task set task_state = 2 where id = %s", (sql_id,))
  225. else:
  226. try:
  227. parse_data(log, resp_json, sql_product_id, sql_pool, sql_shop_id_list)
  228. except Exception as e:
  229. log.error(f"get_resp call parse_data() sql_product_id:{sql_product_id} 获取失败, error:{e}")
  230. @retry(stop=stop_after_attempt(100), wait=wait_fixed(3600), after=after_log)
  231. def jhs_main(log):
  232. """
  233. 主函数
  234. :param log: logger对象
  235. """
  236. log.info(
  237. f'开始运行 {inspect.currentframe().f_code.co_name} 爬虫任务....................................................')
  238. # 配置 MySQL 连接池
  239. sql_pool = MySQLConnectionPool(log=log)
  240. if not sql_pool:
  241. log.error("MySQL数据库连接失败")
  242. raise Exception("MySQL数据库连接失败")
  243. try:
  244. # max_sql_id = sql_pool.select_one("select max(product_id) from jhs_product_record")
  245. # if max_sql_id:
  246. # max_sql_id = max_sql_id[0]
  247. # else:
  248. # max_sql_id = 422342
  249. # log.debug(f"当前数据库中最大的 product_id max_sql_id:{max_sql_id}")
  250. # 从数据库获取需要爬取的 product_id 从最大的id max_sql_id 开始
  251. product_id_list = sql_pool.select_all(
  252. "SELECT id, product_id FROM jhs_task WHERE task_state != 1 AND id > 489000 LIMIT 10000")
  253. # "SELECT id, product_id FROM jhs_task WHERE task_state IN (0, 2) AND id > 420107 LIMIT 10000")
  254. # "SELECT id, product_id FROM jhs_task WHERE task_state IN (0, 2) AND id > %s LIMIT 6000", (max_sql_id,))
  255. # "SELECT id, product_id FROM jhs_task WHERE task_state IN (0, 2) AND id < 376575 ORDER BY id DESC")
  256. product_id_list = [keyword for keyword in product_id_list]
  257. sql_shop_id_list = sql_pool.select_all("SELECT seller_user_id FROM jhs_shop_record")
  258. sql_shop_id_list = [keyword[0] for keyword in sql_shop_id_list]
  259. for sql_product_id in product_id_list:
  260. try:
  261. get_resp(log, sql_product_id, sql_pool, sql_shop_id_list)
  262. except Exception as e:
  263. log.error(f"Loop sql_product_id:{sql_product_id} 获取失败, error:{e}")
  264. sql_pool.update_one("update jhs_task set task_state = 3 where id = %s", (sql_product_id[0],))
  265. except Exception as e:
  266. log.error(f'{inspect.currentframe().f_code.co_name} error: {e}')
  267. finally:
  268. log.info(f'爬虫程序 {inspect.currentframe().f_code.co_name} 运行结束,等待下一轮的采集任务............')
  269. def schedule_task():
  270. """
  271. 设置定时任务
  272. """
  273. jhs_main(log=logger)
  274. schedule.every().day.at("01:31").do(jhs_main, log=logger)
  275. while True:
  276. schedule.run_pending()
  277. time.sleep(1)
  278. if __name__ == '__main__':
  279. schedule_task()
  280. # get_resp(logger, (438807, 438807), MySQLConnectionPool(log=logger),[])