settings.py 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600
  1. # -*- coding: utf-8 -*-
  2. # Author : Charley
  3. # Python : 3.10.8
  4. # Date : 2025/3/24 15:05
  5. import inspect
  6. import requests
  7. from loguru import logger
  8. from bs4 import BeautifulSoup
  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. HEADERS = {
  15. "User-Agent": "Dart/3.5 (dart:io)",
  16. "Accept-Encoding": "gzip",
  17. "Content-Type": "application/json",
  18. "deviceid": "763f77b1-cc16-4369-ac39-a03206ecfb48",
  19. "brand": "Redmi",
  20. "os": "android",
  21. "content-type": "application/json; charset=utf-8",
  22. "authori-zation": "",
  23. "systemversion": "32",
  24. "theme": "dark",
  25. "lang": "zh",
  26. "verse-ua": "d7b3b338008806f1b20427173b983e29",
  27. "version": "1.3.0",
  28. "isphysicaldevice": "true",
  29. "cid": "02931506",
  30. "sktime": "1746343207832",
  31. "sk": "fe8a84f5e1ff81813d9a998d72d1cd99"
  32. }
  33. # headers = {
  34. # "User-Agent": "Dart/3.5 (dart:io)",
  35. # "Accept-Encoding": "gzip",
  36. # "Content-Type": "application/json",
  37. # "deviceid": "763f77b1-cc16-4369-ac39-a03206ecfb48",
  38. # "brand": "Redmi",
  39. # "os": "android",
  40. # "content-type": "application/json; charset=utf-8",
  41. # "authori-zation": "a-22695f440cc94df28b39f3e804696112",
  42. # "systemversion": "32",
  43. # "theme": "dark",
  44. # "lang": "zh",
  45. # "verse-ua": "d7b3b338008806f1b20427173b983e29",
  46. # "version": "1.3.0",
  47. # "isphysicaldevice": "true",
  48. # "sktime": "1746343207832",
  49. # "cid": "02931506",
  50. # "sk": "fe8a84f5e1ff81813d9a998d72d1cd99"
  51. # }
  52. def after_log(retry_state):
  53. """
  54. retry 回调
  55. :param retry_state: RetryCallState 对象
  56. """
  57. # 检查 args 是否存在且不为空
  58. if retry_state.args and len(retry_state.args) > 0:
  59. log = retry_state.args[0] # 获取传入的 logger
  60. else:
  61. log = logger # 使用全局 logger
  62. if retry_state.outcome.failed:
  63. log.warning(
  64. f"Function '{retry_state.fn.__name__}', Attempt {retry_state.attempt_number} Times")
  65. else:
  66. log.info(f"Function '{retry_state.fn.__name__}', Attempt {retry_state.attempt_number} succeeded")
  67. @retry(stop=stop_after_attempt(5), wait=wait_fixed(1), after=after_log)
  68. def get_proxys(log):
  69. """
  70. 获取代理
  71. :return: 代理
  72. """
  73. tunnel = "x371.kdltps.com:15818"
  74. kdl_username = "t13753103189895"
  75. kdl_password = "o0yefv6z"
  76. try:
  77. proxies = {
  78. "http": "http://%(user)s:%(pwd)s@%(proxy)s/" % {"user": kdl_username, "pwd": kdl_password, "proxy": tunnel},
  79. "https": "http://%(user)s:%(pwd)s@%(proxy)s/" % {"user": kdl_username, "pwd": kdl_password, "proxy": tunnel}
  80. }
  81. return proxies
  82. except Exception as e:
  83. log.error(f"Error getting proxy: {e}")
  84. raise e
  85. # def save_shop_list(sql_pool, shop_list):
  86. # """
  87. # 保存店铺数据
  88. # :param sql_pool:
  89. # :param shop_list:
  90. # """
  91. # sql = "INSERT INTO leka_shop_record (shop_id, shop_name, fans_num, group_num, create_time) VALUES (%s, %s, %s, %s, %s)"
  92. # sql_pool.insert_all(sql, shop_list)
  93. # def save_product_list(sql_pool, product_list):
  94. # """
  95. # 保存商品数据
  96. # :param sql_pool:
  97. # :param product_list:
  98. # """
  99. # sql = "INSERT INTO leka_product_record (product_id, no, create_time, title, img, price_sale, total_price, sale_num, spec_config, sort, state, shop_id, shop_name, category, on_sale_time, end_time, finish_time, video_url) VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s)"
  100. # sql_pool.insert_one(sql, product_list)
  101. @retry(stop=stop_after_attempt(5), wait=wait_fixed(1), after=after_log)
  102. def make_request(log, method, url, params=None, data=None, headers=None, proxies=None, timeout=5, token=None):
  103. """
  104. 通用请求函数
  105. :param log: logger对象
  106. :param method: 请求方法 ('GET' 或 'POST')
  107. :param url: 请求的URL
  108. :param params: GET请求的查询参数
  109. :param data: POST请求的数据
  110. :param headers: 请求头
  111. :param proxies: 代理
  112. :param timeout: 请求超时时间
  113. :param token: token
  114. :return: 响应的JSON数据
  115. """
  116. if headers is None:
  117. headers = HEADERS
  118. if 'getHitCardReport' or 'getCardPublicly' in url:
  119. if not token:
  120. token = "a-22695f440cc94df28b39f3e804696112"
  121. headers["authori-zation"] = token
  122. if proxies is None:
  123. proxies = get_proxys(log)
  124. try:
  125. with requests.Session() as session:
  126. if method.upper() == 'GET':
  127. if proxies is None:
  128. response = session.get(url, headers=headers, params=params, timeout=timeout)
  129. else:
  130. response = session.get(url, headers=headers, params=params, proxies=proxies, timeout=timeout)
  131. elif method.upper() == 'POST':
  132. if proxies is None:
  133. response = session.post(url, headers=headers, json=data, timeout=timeout)
  134. # print(response.text)
  135. else:
  136. response = session.post(url, headers=headers, json=data, proxies=proxies, timeout=timeout)
  137. else:
  138. log.error(f"Unsupported request method: {method}")
  139. return None
  140. response.raise_for_status()
  141. data = response.json()
  142. if data["code"] == 200:
  143. log.info(f"Successfully fetched {method} request to {url}")
  144. return data
  145. else:
  146. log.warning(f"Warning {inspect.currentframe().f_code.co_name}: {data['message']}")
  147. return None
  148. except requests.exceptions.RequestException as e:
  149. log.error(f"Error making {method} request to {url}: {e}")
  150. raise e
  151. except ValueError as e:
  152. log.error(f"Error parsing JSON for {method} request to {url}: {e}")
  153. raise e
  154. except Exception as e:
  155. log.error(f"Error making {method} request to {url}: {e}")
  156. raise e
  157. def get_play_back(log, product_id, token):
  158. """
  159. 获取 视频回放链接
  160. :param log: logger对象
  161. :param product_id: product_id
  162. :param token: token
  163. """
  164. log.info(f"Starting to fetch playback for product_id {product_id}")
  165. url = "https://api.luckycards.com.cn/api/front/c/product/productDetailDynamics"
  166. params = {
  167. # "code": "LCS1254174"
  168. "code": product_id
  169. }
  170. try:
  171. response = make_request(log, 'GET', url, params=params, token=token)
  172. if response:
  173. items = response.get("data", {})
  174. normalLiving = items.get("normalLiving", {})
  175. playback = normalLiving.get("playback")
  176. return playback
  177. else:
  178. return None
  179. except Exception as e:
  180. log.error(f"Error fetching playback {product_id}: {e}")
  181. return None
  182. def clean_texts(html_text):
  183. """
  184. 使用 BeautifulSoup 解析并获取纯文本
  185. :param html_text: 待解析的HTML格式的数据
  186. :return: clean_text -> 解析后的数据
  187. """
  188. if not html_text:
  189. return ""
  190. soup = BeautifulSoup(html_text, 'html.parser')
  191. # clean_text = soup.get_text(separator=' ', strip=True)
  192. clean_text = soup.get_text(strip=True)
  193. # 替换   为普通空格
  194. clean_text = clean_text.replace(' ', ' ')
  195. return clean_text
  196. def parse_product_items(log, items, sql_pool, product_id, token):
  197. """
  198. 解析 产品信息
  199. :param log: logger对象
  200. :param items: 请求response
  201. :param sql_pool: MySQL连接池对象
  202. :param product_id: product_id
  203. :param token: token
  204. """
  205. if not items:
  206. log.warning(f"Warning {inspect.currentframe().f_code.co_name}: No items found")
  207. return
  208. no = items.get("id")
  209. create_time = items.get("publishTime")
  210. title = items.get("productName")
  211. img = items.get("productImageIndex")
  212. price_sale = items.get("unitPriceStr")
  213. total_price = items.get("totalSalePrice")
  214. sale_num = items.get("saleCount") # 售出数量
  215. spec_config = items.get("hitCardStandard") # 规格
  216. sort = items.get("series") # 分类 0:全部 1:原盒 2:幸运盒 3:福盒?
  217. state = items.get("status")
  218. shop_id = items.get("merchantCode")
  219. shop_name = items.get("merchantName")
  220. category = items.get("brandId")
  221. on_sale_time = items.get("onlineTime")
  222. end_time = items.get("endTime")
  223. finish_time = items.get("finishTime")
  224. # content = items.get("purchaseNotes")
  225. # if content:
  226. # content = content.replace("<p>", "").replace("</p>", "")
  227. # brief = items.get("brief")
  228. product_detail = items.get("productDetail")
  229. if product_detail:
  230. product_detail = clean_texts(product_detail)
  231. # print('product_detail:',product_detail)
  232. video_url = get_play_back(log, product_id, token)
  233. hit_card_desc = items.get("hitCardDesc") # 赠品介绍
  234. open_mode = items.get("openMode") # 随机球队
  235. open_mode_comment = items.get("openModeComment") # 随机球队 说明
  236. random_mode = items.get("randomMode") # 即买即随
  237. random_mode_comment = items.get("randomModeComment") # 即买即随 说明
  238. info_dict = {
  239. "no": no,
  240. "create_time": create_time,
  241. "title": title,
  242. "img": img,
  243. "price_sale": price_sale,
  244. "total_price": total_price,
  245. "sale_num": sale_num,
  246. "spec_config": spec_config,
  247. "sort": sort,
  248. "state": state,
  249. "shop_id": shop_id,
  250. "shop_name": shop_name,
  251. "category": category,
  252. "on_sale_time": on_sale_time,
  253. "end_time": end_time,
  254. "finish_time": finish_time,
  255. "product_detail": product_detail,
  256. "video_url": video_url,
  257. "hit_card_desc": hit_card_desc,
  258. "open_mode": open_mode,
  259. "open_mode_comment": open_mode_comment,
  260. "random_mode": random_mode,
  261. "random_mode_comment": random_mode_comment,
  262. }
  263. # print(info_dict)
  264. # sql_pool.insert_one_or_dict(table="leka_product_record", data=info_dict)
  265. sql_pool.update_one_or_dict(table="leka_product_record", data=info_dict, condition={"product_id": product_id})
  266. @retry(stop=stop_after_attempt(5), wait=wait_fixed(1), after=after_log)
  267. def get_product_details(log, product_id, sql_pool, token):
  268. """
  269. 获取 商品详情 单条 信息
  270. :param log: logger对象
  271. :param product_id: product_id
  272. :param sql_pool: MySQL连接池对象
  273. :param token: token
  274. """
  275. log.debug(f"Getting product details for {product_id}")
  276. url = "https://api.luckycards.com.cn/api/front/c/product/productDetail"
  277. params = {
  278. # "code": "LCS1254079"
  279. "code": product_id
  280. }
  281. try:
  282. response = make_request(log, 'GET', url, params=params, token=token)
  283. if response:
  284. parse_product_items(log, response.get("data"), sql_pool, product_id, token)
  285. else:
  286. log.error(f"Error getting product details for {product_id}: {response.get('msg')}")
  287. except Exception as e:
  288. log.error(f"Error getting product details for {product_id}: {e}")
  289. def get_product_detail_list(log, sql_pool, token):
  290. """
  291. 获取 商品详情 列表 信息
  292. :param log: logger对象
  293. :param sql_pool: MySQL连接池对象
  294. :param token: token
  295. """
  296. sql_product_id_list = sql_pool.select_all("SELECT product_id FROM leka_product_record WHERE no IS NULL")
  297. sql_product_id_list = [item[0] for item in sql_product_id_list]
  298. for product_id in sql_product_id_list:
  299. try:
  300. get_product_details(log, product_id, sql_pool, token)
  301. except Exception as e:
  302. log.error(f"Error get_product_detail_list fetching product {product_id}: {e}")
  303. continue
  304. def parse_player_items(log, items, sql_pool, product_id):
  305. """
  306. 解析 卡密公示 信息
  307. :param log: logger对象
  308. :param items: 请求response
  309. :param product_id: product_id
  310. :param sql_pool: MySQL连接池对象
  311. """
  312. if not items:
  313. log.warning(f"Warning {inspect.currentframe().f_code.co_name}: No items found")
  314. return
  315. player_list = []
  316. for item in items:
  317. # print(item)
  318. user_code = item.get("userCode")
  319. user_id = item.get("userId")
  320. user_name = item.get("nickName")
  321. num = item.get("cardCount")
  322. # info = (product_id, user_code, num, user_id, user_name)
  323. info_dict = {
  324. "product_id": product_id,
  325. "user_code": user_code,
  326. "num": num,
  327. "user_id": user_id,
  328. "user_name": user_name
  329. }
  330. # print(info_dict)
  331. player_list.append(info_dict)
  332. sql_pool.insert_many(table='leka_player_record', data_list=player_list)
  333. sql_pool.update_one("update leka_product_record set km_state = 1 where product_id = %s", (product_id,))
  334. @retry(stop=stop_after_attempt(5), wait=wait_fixed(1), after=after_log)
  335. def get_player_list(log, product_id, sql_pool, token):
  336. """
  337. 抓取 kami公示 信息
  338. :param log: logger对象
  339. :param product_id: product_id
  340. :param sql_pool: MySQL连接池对象
  341. :param token: token
  342. """
  343. log.debug(f"Getting player list for {product_id}")
  344. url = "https://api.luckycards.com.cn/api/front/c/card/getCardPublicly"
  345. last_id = 0 # 初始lastId为0
  346. total_players = 0
  347. while True:
  348. data = {
  349. "keyword": "",
  350. "lastUserId": last_id,
  351. "productCode": product_id,
  352. "publiclyType": 2, # 1:赠品维度 2:玩家维度
  353. }
  354. # print(data)
  355. try:
  356. response = make_request(log, 'POST', url, data=data, token=token)
  357. if not response:
  358. log.error(f"Error getting player list for {product_id}: Empty response")
  359. break
  360. items = response.get("data", [])
  361. if not items:
  362. log.info(f"No more players found for product {product_id}")
  363. sql_pool.update_one("update leka_product_record set km_state = 3 where product_id = %s", (product_id,))
  364. break
  365. # 处理当前页数据
  366. parse_player_items(log, items, sql_pool, product_id)
  367. total_players += len(items)
  368. # 如果获取数量超过50条,说明已经获取到所有数据,结束循环
  369. if total_players > 50:
  370. log.debug(f"Total players found for product {product_id}: {total_players}")
  371. break
  372. # 如果获取数量不足20条,说明是最后一页
  373. if len(items) < 20:
  374. log.info(f"Last page detected for product {product_id} (got {len(items)} items)")
  375. break
  376. # 更新lastId为最后一条的userId
  377. last_id = items[-1].get("userId")
  378. # print(last_id)
  379. if not last_id:
  380. log.error("API response missing userId in last item, cannot paginate")
  381. break
  382. # 避免频繁请求
  383. # time.sleep(0.5)
  384. except Exception as e:
  385. log.error(f"Error getting player list for {product_id} at lastId {last_id}: {e}")
  386. break
  387. log.info(f"Finished fetching players for product {product_id}, total: {total_players}")
  388. def get_players(log, sql_pool, token):
  389. """
  390. 抓取 kami公示 信息
  391. :param log: logger对象
  392. :param sql_pool: MySQL连接池对象
  393. :param token: token
  394. """
  395. product_list = sql_pool.select_all("SELECT product_id FROM leka_product_record WHERE km_state IN (0, 3)")
  396. product_list = [product_id[0] for product_id in product_list]
  397. # token = sql_pool.select_one("SELECT token FROM leka_token")
  398. # token = token[0]
  399. if not product_list:
  400. log.warning(f"Warning {inspect.currentframe().f_code.co_name}: No product_id found")
  401. return
  402. else:
  403. log.info(f"Start fetching players data. Total products: {len(product_list)}")
  404. for product_id in product_list:
  405. try:
  406. get_player_list(log, product_id, sql_pool, token)
  407. except Exception as e:
  408. log.error(f"Error fetching product {product_id}: {e}")
  409. continue
  410. @retry(stop=stop_after_attempt(5), wait=wait_fixed(1), after=after_log)
  411. def get_report_one_page(log, sql_pool, productCode, page, last_id, token):
  412. """
  413. 获取 拆卡报告 单页的信息
  414. :param log: logger对象
  415. :param sql_pool: MySQL连接池对象
  416. :param productCode: product_id
  417. :param page: 页码
  418. :param last_id: last_id
  419. :param token: token
  420. """
  421. url = "https://api.luckycards.com.cn/api/front/c/card/getHitCardReport"
  422. data = {
  423. "keyword": "",
  424. "page": page,
  425. "lastId": last_id,
  426. # "productCode": "LCS1254213"
  427. "productCode": productCode
  428. }
  429. log.info(f"Getting report data for: {productCode}, Page: {page}")
  430. try:
  431. response = make_request(log, 'POST', url, data=data, token=token)
  432. # print(response)
  433. if response:
  434. items = response.get("data", [])
  435. if items:
  436. info_list = []
  437. for item in items:
  438. card_id = item.get("orderNo")
  439. card_name = item.get("cardSecret")
  440. create_time = item.get("drawTime")
  441. imgs = item.get("hitPic")
  442. user_id = item.get("userCode")
  443. user_name = item.get("nickName")
  444. shop_id = item.get("merchantCode")
  445. shop_name = item.get("merchantName")
  446. card_desc = item.get("hitCardDesc")
  447. # info = (card_id, card_name, create_time, imgs, user_id, user_name, shop_id, shop_name, card_desc)
  448. info_dict = {
  449. "product_id": productCode,
  450. "card_id": card_id,
  451. "card_name": card_name,
  452. "create_time": create_time,
  453. "imgs": imgs,
  454. "user_id": user_id,
  455. "user_name": user_name,
  456. "shop_id": shop_id,
  457. "shop_name": shop_name,
  458. "card_desc": card_desc
  459. }
  460. # print(info_dict)
  461. info_list.append(info_dict)
  462. sql_pool.insert_many(table='leka_report_record', data_list=info_list)
  463. log.info(f"Successfully saved {len(items)} report items")
  464. return items[-1].get("userCode"), len(items)
  465. else:
  466. log.warning(f"Warning {inspect.currentframe().f_code.co_name}: No items found")
  467. sql_pool.update_one("update leka_product_record set report_state = 3 where product_id = %s",
  468. (productCode,))
  469. return 0, 0
  470. else:
  471. log.error(f"Error getting report data: {response.get('msg')}")
  472. return 0
  473. except Exception as e:
  474. log.error(f"Error getting report data: {e}")
  475. raise e
  476. def get_report_list(log, sql_pool, product_id, token):
  477. """
  478. 抓取 拆卡报告 单个product_id 所有页码的 信息
  479. :param log: logger对象
  480. :param sql_pool: MySQL连接池对象
  481. :param product_id: product_id
  482. :param token: token
  483. """
  484. # log.info(f"Start fetching report data. Product id: {product_id}")
  485. page = 1
  486. last_id = 0
  487. # while True:
  488. try:
  489. last_d, len_item = get_report_one_page(log, sql_pool, product_id, page, last_id, token)
  490. # if len_item != 0 and len_item < 20:
  491. log.info(f"Finished fetching report data for product {product_id}, total: {len_item}")
  492. sql_pool.update_one("update leka_product_record set report_state = 1 where product_id = %s", (product_id,))
  493. # # 如果获取数量不足20条,说明是最后一页 ***暂时没找到第二页的***
  494. # if len_item < 20:
  495. # log.info(f"Last page detected for product {product_id} (got {len_item} items)")
  496. # break
  497. #
  498. # # 更新lastId为最后一条的userId
  499. # last_id = last_d
  500. # if not last_id:
  501. # log.error("API response missing userId in last item, cannot paginate")
  502. # break
  503. #
  504. # page += 1
  505. except Exception as e:
  506. log.error(f"Error getting report data: {e}")
  507. # break
  508. def get_reports(log, sql_pool, token):
  509. """
  510. 抓取 拆卡报告 信息
  511. :param log: logger对象
  512. :param sql_pool: MySQL连接池对象
  513. :param token: token
  514. """
  515. product_list = sql_pool.select_all("SELECT product_id FROM leka_product_record WHERE report_state IN (0, 3)")
  516. product_list = [product_id[0] for product_id in product_list]
  517. # token = sql_pool.select_one("SELECT token FROM leka_token")
  518. # token = token[0]
  519. if not product_list:
  520. log.warning(f"Warning {inspect.currentframe().f_code.co_name}: No product_id found")
  521. return
  522. else:
  523. log.info(f"Start fetching report data. Total products: {len(product_list)}")
  524. for product_id in product_list:
  525. try:
  526. get_report_list(log, sql_pool, product_id, token)
  527. except Exception as e:
  528. log.error(f"Error fetching product {product_id}: {e}")
  529. continue
  530. if __name__ == '__main__':
  531. pass
  532. # pid = 'LCS1254213'
  533. # pid = 'LCS1253418'
  534. # pid = 'LCS1256332'
  535. # from mysql_pool import MySQLConnectionPool
  536. # sql_pool_ = MySQLConnectionPool(log=logger)
  537. # get_reports(logger, None)
  538. # get_player_list(logger, pid, None)
  539. # get_product_details(logger, 'LCS1255968', sql_pool_)