settings.py 21 KB

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