settings.py 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603
  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": "2.0.0",
  28. "isphysicaldevice": "true",
  29. "cid": "53780516",
  30. "sktime": "1750829899149",
  31. "sk": "2b325cf1497b6fbe300f8cf609b23a0a"
  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. # print(data)
  143. if data["code"] == 200:
  144. log.info(f"Successfully fetched {method} request to {url}")
  145. return data
  146. else:
  147. log.warning(f"Warning {inspect.currentframe().f_code.co_name}: {data['message']}")
  148. return None
  149. except requests.exceptions.RequestException as e:
  150. log.error(f"Error making {method} request to {url}: {e}")
  151. raise e
  152. except ValueError as e:
  153. log.error(f"Error parsing JSON for {method} request to {url}: {e}")
  154. raise e
  155. except Exception as e:
  156. log.error(f"Error making {method} request to {url}: {e}")
  157. raise e
  158. def get_play_back(log, product_id, token):
  159. """
  160. 获取 视频回放链接
  161. :param log: logger对象
  162. :param product_id: product_id
  163. :param token: token
  164. """
  165. log.info(f"Starting to fetch playback for product_id {product_id}")
  166. url = "https://api.luckycards.com.cn/api/front/c/product/productDetailDynamics"
  167. params = {
  168. # "code": "LCS1254174"
  169. "code": product_id
  170. }
  171. try:
  172. response = make_request(log, 'GET', url, params=params, token=token)
  173. if response:
  174. items = response.get("data", {})
  175. normalLiving = items.get("normalLiving", {})
  176. playback = normalLiving.get("playback")
  177. return playback
  178. else:
  179. return None
  180. except Exception as e:
  181. log.error(f"Error fetching playback {product_id}: {e}")
  182. return None
  183. def clean_texts(html_text):
  184. """
  185. 使用 BeautifulSoup 解析并获取纯文本
  186. :param html_text: 待解析的HTML格式的数据
  187. :return: clean_text -> 解析后的数据
  188. """
  189. if not html_text:
  190. return ""
  191. soup = BeautifulSoup(html_text, 'html.parser')
  192. # clean_text = soup.get_text(separator=' ', strip=True)
  193. clean_text = soup.get_text(strip=True)
  194. # 替换   为普通空格
  195. clean_text = clean_text.replace(' ', ' ')
  196. return clean_text
  197. def parse_product_items(log, items, sql_pool, product_id, token):
  198. """
  199. 解析 产品信息
  200. :param log: logger对象
  201. :param items: 请求response
  202. :param sql_pool: MySQL连接池对象
  203. :param product_id: product_id
  204. :param token: token
  205. """
  206. if not items:
  207. log.warning(f"Warning {inspect.currentframe().f_code.co_name}: No items found")
  208. return
  209. no = items.get("id")
  210. create_time = items.get("publishTime")
  211. title = items.get("productName")
  212. img = items.get("productImageIndex")
  213. price_sale = items.get("unitPriceStr")
  214. total_price = items.get("totalSalePrice")
  215. sale_num = items.get("saleCount") # 售出数量
  216. spec_config = items.get("hitCardStandard") # 规格
  217. sort = items.get("series") # 分类 0:全部 1:原盒 2:幸运盒 3:福盒?
  218. state = items.get("status")
  219. shop_id = items.get("merchantCode")
  220. shop_name = items.get("merchantName")
  221. category = items.get("brandId")
  222. on_sale_time = items.get("onlineTime")
  223. end_time = items.get("endTime")
  224. finish_time = items.get("finishTime")
  225. # content = items.get("purchaseNotes")
  226. # if content:
  227. # content = content.replace("<p>", "").replace("</p>", "")
  228. # brief = items.get("brief")
  229. product_detail = items.get("productDetail")
  230. if product_detail:
  231. product_detail = clean_texts(product_detail)
  232. # print('product_detail:',product_detail)
  233. video_url = get_play_back(log, product_id, token)
  234. hit_card_desc = items.get("hitCardDesc") # 赠品介绍
  235. open_mode = items.get("openMode") # 随机球队
  236. open_mode_comment = items.get("openModeComment") # 随机球队 说明
  237. random_mode = items.get("randomMode") # 即买即随
  238. random_mode_comment = items.get("randomModeComment") # 即买即随 说明
  239. info_dict = {
  240. "no": no,
  241. "create_time": create_time,
  242. "title": title,
  243. "img": img,
  244. "price_sale": price_sale,
  245. "total_price": total_price,
  246. "sale_num": sale_num,
  247. "spec_config": spec_config,
  248. "sort": sort,
  249. "state": state,
  250. "shop_id": shop_id,
  251. "shop_name": shop_name,
  252. "category": category,
  253. "on_sale_time": on_sale_time,
  254. "end_time": end_time,
  255. "finish_time": finish_time,
  256. "product_detail": product_detail,
  257. "video_url": video_url,
  258. "hit_card_desc": hit_card_desc,
  259. "open_mode": open_mode,
  260. "open_mode_comment": open_mode_comment,
  261. "random_mode": random_mode,
  262. "random_mode_comment": random_mode_comment,
  263. }
  264. # print(info_dict)
  265. # sql_pool.insert_one_or_dict(table="leka_product_record", data=info_dict)
  266. sql_pool.update_one_or_dict(table="leka_product_record", data=info_dict, condition={"product_id": product_id})
  267. @retry(stop=stop_after_attempt(5), wait=wait_fixed(1), after=after_log)
  268. def get_product_details(log, product_id, sql_pool, token):
  269. """
  270. 获取 商品详情 单条 信息
  271. :param log: logger对象
  272. :param product_id: product_id
  273. :param sql_pool: MySQL连接池对象
  274. :param token: token
  275. """
  276. log.debug(f"Getting product details for {product_id}")
  277. url = "https://api.luckycards.com.cn/api/front/c/product/productDetail"
  278. params = {
  279. # "code": "LCS1254079"
  280. "code": product_id
  281. }
  282. try:
  283. response = make_request(log, 'GET', url, params=params, token=token)
  284. if response:
  285. parse_product_items(log, response.get("data"), sql_pool, product_id, token)
  286. else:
  287. log.error(f"Error getting product details for {product_id}: {response.get('msg')}")
  288. except Exception as e:
  289. log.error(f"Error getting product details for {product_id}: {e}")
  290. def get_product_detail_list(log, sql_pool, token):
  291. """
  292. 获取 商品详情 列表 信息
  293. :param log: logger对象
  294. :param sql_pool: MySQL连接池对象
  295. :param token: token
  296. """
  297. sql_product_id_list = sql_pool.select_all("SELECT product_id FROM leka_product_record WHERE no IS NULL")
  298. sql_product_id_list = [item[0] for item in sql_product_id_list]
  299. for product_id in sql_product_id_list:
  300. try:
  301. get_product_details(log, product_id, sql_pool, token)
  302. except Exception as e:
  303. log.error(f"Error get_product_detail_list fetching product {product_id}: {e}")
  304. continue
  305. def parse_player_items(log, items, sql_pool, product_id):
  306. """
  307. 解析 卡密公示 信息
  308. :param log: logger对象
  309. :param items: 请求response
  310. :param product_id: product_id
  311. :param sql_pool: MySQL连接池对象
  312. """
  313. if not items:
  314. log.warning(f"Warning {inspect.currentframe().f_code.co_name}: No items found")
  315. return
  316. player_list = []
  317. for item in items:
  318. # print(item)
  319. user_code = item.get("userCode")
  320. user_id = item.get("userId")
  321. user_name = item.get("nickName")
  322. num = item.get("cardCount")
  323. # info = (product_id, user_code, num, user_id, user_name)
  324. info_dict = {
  325. "product_id": product_id,
  326. "user_code": user_code,
  327. "num": num,
  328. "user_id": user_id,
  329. "user_name": user_name
  330. }
  331. # print(info_dict)
  332. player_list.append(info_dict)
  333. sql_pool.insert_many(table='leka_player_record', data_list=player_list)
  334. sql_pool.update_one("update leka_product_record set km_state = 1 where product_id = %s", (product_id,))
  335. @retry(stop=stop_after_attempt(5), wait=wait_fixed(1), after=after_log)
  336. def get_player_list(log, product_id, sql_pool, token):
  337. """
  338. 抓取 kami公示 信息
  339. :param log: logger对象
  340. :param product_id: product_id
  341. :param sql_pool: MySQL连接池对象
  342. :param token: token
  343. """
  344. log.debug(f"Getting player list for {product_id}")
  345. url = "https://api.luckycards.com.cn/api/front/c/card/getCardPublicly"
  346. last_id = 0 # 初始lastId为0
  347. total_players = 0
  348. while True:
  349. data = {
  350. "keyword": "",
  351. "lastUserId": last_id,
  352. "productCode": product_id,
  353. "publiclyType": 2, # 1:赠品维度 2:玩家维度
  354. }
  355. # print(data)
  356. try:
  357. response = make_request(log, 'POST', url, data=data, token=token)
  358. if not response:
  359. log.error(f"Error getting player list for {product_id}: Empty response")
  360. break
  361. items = response.get("data", [])
  362. if not items:
  363. log.info(f"No more players found for product {product_id}")
  364. sql_pool.update_one("update leka_product_record set km_state = 3 where product_id = %s", (product_id,))
  365. break
  366. # 处理当前页数据
  367. parse_player_items(log, items, sql_pool, product_id)
  368. total_players += len(items)
  369. # 如果获取数量超过50条,说明已经获取到所有数据,结束循环
  370. if total_players > 50:
  371. log.debug(f"Total players found for product {product_id}: {total_players}")
  372. break
  373. # 如果获取数量不足20条,说明是最后一页
  374. if len(items) < 20:
  375. log.info(f"Last page detected for product {product_id} (got {len(items)} items)")
  376. break
  377. # 更新lastId为最后一条的userId
  378. last_id = items[-1].get("userId")
  379. # print(last_id)
  380. if not last_id:
  381. log.error("API response missing userId in last item, cannot paginate")
  382. break
  383. # 避免频繁请求
  384. # time.sleep(0.5)
  385. except Exception as e:
  386. log.error(f"Error getting player list for {product_id} at lastId {last_id}: {e}")
  387. break
  388. log.info(f"Finished fetching players for product {product_id}, total: {total_players}")
  389. def get_players(log, sql_pool, token):
  390. """
  391. 抓取 kami公示 信息
  392. :param log: logger对象
  393. :param sql_pool: MySQL连接池对象
  394. :param token: token
  395. """
  396. product_list = sql_pool.select_all("SELECT product_id FROM leka_product_record WHERE km_state IN (0, 3)")
  397. product_list = [product_id[0] for product_id in product_list]
  398. # token = sql_pool.select_one("SELECT token FROM leka_token")
  399. # token = token[0]
  400. if not product_list:
  401. log.warning(f"Warning {inspect.currentframe().f_code.co_name}: No product_id found")
  402. return
  403. else:
  404. log.info(f"Start fetching players data. Total products: {len(product_list)}")
  405. for product_id in product_list:
  406. try:
  407. get_player_list(log, product_id, sql_pool, token)
  408. except Exception as e:
  409. log.error(f"Error fetching product {product_id}: {e}")
  410. continue
  411. @retry(stop=stop_after_attempt(5), wait=wait_fixed(1), after=after_log)
  412. def get_report_one_page(log, sql_pool, productCode, page, last_id, token):
  413. """
  414. 获取 拆卡报告 单页的信息
  415. :param log: logger对象
  416. :param sql_pool: MySQL连接池对象
  417. :param productCode: product_id
  418. :param page: 页码
  419. :param last_id: last_id
  420. :param token: token
  421. """
  422. url = "https://api.luckycards.com.cn/api/front/c/card/getHitCardReport"
  423. data = {
  424. "keyword": "",
  425. "page": page,
  426. "lastId": last_id,
  427. # "productCode": "LCS1254213"
  428. "productCode": productCode
  429. }
  430. log.info(f"Getting report data for: {productCode}, Page: {page}")
  431. try:
  432. response = make_request(log, 'POST', url, data=data, token=token)
  433. # print(response)
  434. if response:
  435. items = response.get("data", [])
  436. if items:
  437. info_list = []
  438. for item in items:
  439. card_id = item.get("orderNo")
  440. card_name = item.get("cardSecret")
  441. create_time = item.get("drawTime")
  442. imgs = item.get("hitPic")
  443. user_id = item.get("userCode")
  444. user_name = item.get("nickName")
  445. shop_id = item.get("merchantCode")
  446. shop_name = item.get("merchantName")
  447. card_desc = item.get("hitCardDesc")
  448. # info = (card_id, card_name, create_time, imgs, user_id, user_name, shop_id, shop_name, card_desc)
  449. info_dict = {
  450. "product_id": productCode,
  451. "card_id": card_id,
  452. "card_name": card_name,
  453. "create_time": create_time,
  454. "imgs": imgs,
  455. "user_id": user_id,
  456. "user_name": user_name,
  457. "shop_id": shop_id,
  458. "shop_name": shop_name,
  459. "card_desc": card_desc
  460. }
  461. # print(info_dict)
  462. info_list.append(info_dict)
  463. sql_pool.insert_many(table='leka_report_record', data_list=info_list)
  464. log.info(f"Successfully saved {len(items)} report items")
  465. return items[-1].get("userCode"), len(items)
  466. else:
  467. log.warning(f"Warning {inspect.currentframe().f_code.co_name}: No items found")
  468. sql_pool.update_one("update leka_product_record set report_state = 3 where product_id = %s",
  469. (productCode,))
  470. return 0, 0
  471. else:
  472. log.error(f"Error getting report data: {response.get('msg')}")
  473. return 0
  474. except Exception as e:
  475. log.error(f"Error getting report data: {e}")
  476. raise e
  477. def get_report_list(log, sql_pool, product_id, token):
  478. """
  479. 抓取 拆卡报告 单个product_id 所有页码的 信息
  480. :param log: logger对象
  481. :param sql_pool: MySQL连接池对象
  482. :param product_id: product_id
  483. :param token: token
  484. """
  485. # log.info(f"Start fetching report data. Product id: {product_id}")
  486. page = 1
  487. last_id = 0
  488. # while True:
  489. try:
  490. last_d, len_item = get_report_one_page(log, sql_pool, product_id, page, last_id, token)
  491. # if len_item != 0 and len_item < 20:
  492. log.info(f"Finished fetching report data for product {product_id}, total: {len_item}")
  493. sql_pool.update_one("update leka_product_record set report_state = 1 where product_id = %s", (product_id,))
  494. # # 如果获取数量不足20条,说明是最后一页 ***暂时没找到第二页的***
  495. # if len_item < 20:
  496. # log.info(f"Last page detected for product {product_id} (got {len_item} items)")
  497. # break
  498. #
  499. # # 更新lastId为最后一条的userId
  500. # last_id = last_d
  501. # if not last_id:
  502. # log.error("API response missing userId in last item, cannot paginate")
  503. # break
  504. #
  505. # page += 1
  506. except Exception as e:
  507. log.error(f"Error getting report data: {e}")
  508. # break
  509. def get_reports(log, sql_pool, token):
  510. """
  511. 抓取 拆卡报告 信息
  512. :param log: logger对象
  513. :param sql_pool: MySQL连接池对象
  514. :param token: token
  515. """
  516. product_list = sql_pool.select_all("SELECT product_id FROM leka_product_record WHERE report_state IN (0, 3)")
  517. product_list = [product_id[0] for product_id in product_list]
  518. # token = sql_pool.select_one("SELECT token FROM leka_token")
  519. # token = token[0]
  520. if not product_list:
  521. log.warning(f"Warning {inspect.currentframe().f_code.co_name}: No product_id found")
  522. return
  523. else:
  524. log.info(f"Start fetching report data. Total products: {len(product_list)}")
  525. for product_id in product_list:
  526. try:
  527. get_report_list(log, sql_pool, product_id, token)
  528. except Exception as e:
  529. log.error(f"Error fetching product {product_id}: {e}")
  530. continue
  531. if __name__ == '__main__':
  532. pass
  533. # pid = 'LCS1254213'
  534. # pid = 'LCS1253418'
  535. # pid = 'LCS1256332'
  536. # from mysql_pool import MySQLConnectionPool
  537. # sql_pool_ = MySQLConnectionPool(log=logger)
  538. # get_reports(logger, None)
  539. # get_player_list(logger, pid, None)
  540. # get_product_details(logger, 'LCS1255968', sql_pool_)