settings.py 21 KB

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