1
0

yaoex_crawl.py 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469
  1. import json
  2. import random
  3. import time
  4. import requests
  5. from commons.Logger import get_spider_logger
  6. from commons.scheduler import CrawlerScheduler
  7. import base64
  8. from Crypto.Cipher import AES
  9. from Crypto.Util.Padding import unpad
  10. from pipelines.drug_pipelines import DrugPipeline
  11. from area_info.city_name_to_id import get_city
  12. import hashlib
  13. logger = get_spider_logger("yaoex")
  14. TOKEN = "Sm45MzRmREtiaStVTnJORXEySHhYYzNwUmQ2RUprWXlwelRDem4wV2RZUCtUUU5jMGVCVTRYYjNLVjdNSnFWSjg1YStxWllGQ2RQSExjaEVqU0dOaDFJczl4bTB1V09CZHZzVml2dU0xazd3UDdla3FTUzZBZlZkMHFSVHlaaDhDcFp3SWNDb3JNSDhuNC9vUzI1RVdEaU01YjcxQW5TS21Sdy90ZDRENi9VR2E0SW5wOWF4UE1VZ0poTDhhVkJtP2FwcElkPTEyNTAma2V5SWQ9MTI1MA=="
  15. # 平台常量(API 调度用)
  16. PLATFORM_ID = 6
  17. YYC_DEVICE_ID = "181930302811"
  18. HEARTBEAT_INTERVAL_SECONDS = 60
  19. TASK_API_BASE = "http://pricesys2.kailin.com.cn:8083/api/collect_task"
  20. TASK_API_TOKEN = "zhijiayun_crawler_2026"
  21. TASK_PULL_URL = TASK_API_BASE + "/pull"
  22. TASK_HEARTBEAT_URL = TASK_API_BASE + "/heartbeat"
  23. headers = {
  24. "Accept": "application/json, text/plain, */*",
  25. "Accept-Language": "zh-CN,zh;q=0.9",
  26. "Connection": "keep-alive",
  27. "Content-Type": "application/x-www-form-urlencoded",
  28. "Origin": "https://mall.yaoex.com",
  29. "Referer": "https://mall.yaoex.com/",
  30. "Sec-Fetch-Dest": "empty",
  31. "Sec-Fetch-Mode": "cors",
  32. "Sec-Fetch-Site": "cross-site",
  33. "User-Agent": (
  34. "Mozilla/5.0 (Windows NT 10.0; Win64; x64) "
  35. "AppleWebKit/537.36 (KHTML, like Gecko) "
  36. "Chrome/146.0.0.0 Safari/537.36"
  37. ),
  38. "X-Request-Agent": "Axios",
  39. "X-Requested-With": "XMLHttpRequest",
  40. "sec-ch-ua": '"Chromium";v="146", "Not-A.Brand";v="24", "Google Chrome";v="146"',
  41. "sec-ch-ua-mobile": "?0",
  42. "sec-ch-ua-platform": '"Windows"',
  43. }
  44. REQUEST_RETRY_COUNT = 3
  45. REQUEST_TIMEOUT_SEC = 20
  46. class YaoexCrawler:
  47. def __init__(self, drug_dict=None):
  48. self.token = TOKEN
  49. self.user_id = "181680"
  50. self.platform = 6
  51. self.task_dict = drug_dict or {}
  52. self.collect_task_id = None
  53. self.account_name = None
  54. self.pipeline = DrugPipeline("yaoex")
  55. self.scheduler = CrawlerScheduler(YYC_DEVICE_ID, str(PLATFORM_ID), heartbeat_interval=HEARTBEAT_INTERVAL_SECONDS)
  56. # 独立回告(不依赖 commons,commons 经常变)
  57. self.TASK_REPORT_URL = "http://pricesys2.kailin.com.cn:8083/api/collect_task/report"
  58. self.TASK_API_TOKEN = "zhijiayun_crawler_2026"
  59. if self.task_dict:
  60. self.get_product_data()
  61. self.is_success = True
  62. self.is_not_product = 0
  63. # ---------- API report helpers ----------
  64. def _send_report(self, params: dict, log_msg: str):
  65. try:
  66. resp = requests.post(
  67. self.TASK_REPORT_URL, json=params, timeout=10,
  68. headers={'X-Crawler-Token': self.TASK_API_TOKEN},
  69. )
  70. if resp.status_code == 200:
  71. try:
  72. data = resp.json()
  73. if data.get("code") == "success":
  74. logger.info("回告成功:%s", log_msg)
  75. return "success"
  76. else:
  77. msg = data.get("msg", "")
  78. if "已达平台限额" in msg or "限额" in msg:
  79. logger.warning("回告接口返回限额错误:code=%s, msg=%s", data.get('code'), msg)
  80. return "limit_reached"
  81. else:
  82. logger.warning("回告接口返回错误:code=%s, msg=%s", data.get('code'), msg)
  83. return "error"
  84. except ValueError:
  85. logger.warning("回告响应非 JSON:%s", resp.text[:200])
  86. return "error"
  87. else:
  88. logger.warning("回告 HTTP %s", resp.status_code)
  89. return "error"
  90. except Exception as e:
  91. logger.error("回告失败:%s,错误:%s", log_msg, str(e))
  92. return "error"
  93. def _report_start(self):
  94. payload = {
  95. "task_id": self.task_id,
  96. "platform": str(self.platform),
  97. "username": YYC_DEVICE_ID,
  98. "current_page": 0,
  99. "total_pages": 0,
  100. "is_finished": 0,
  101. }
  102. logger.info("上报开始 task_id=%s", self.task_id)
  103. return self._send_report(payload, "开始上报(is_finished=0)")
  104. def _report_progress(self, current_page: int, total_pages: int = 0):
  105. payload = {
  106. "task_id": self.task_id,
  107. "platform": str(self.platform),
  108. "username": YYC_DEVICE_ID,
  109. "current_page": current_page,
  110. "total_pages": total_pages,
  111. "is_finished": 0,
  112. }
  113. return self._send_report(payload, f"进度上报 page={current_page}")
  114. def _report_end(self, success: bool, real_count: int, page_no: int = 0, total_pages: int = 0):
  115. payload = {
  116. "task_id": self.task_id,
  117. "platform": str(self.platform),
  118. "username": YYC_DEVICE_ID,
  119. "current_page": page_no,
  120. "total_pages": total_pages if total_pages > 0 else page_no,
  121. "crawled_count": real_count,
  122. "is_finished": 1, # 到了 _report_end 必然已经跑完了
  123. }
  124. if not success:
  125. payload["exception_type"] = 5
  126. payload["remark"] = "采集异常或API请求失败"
  127. logger.info("上报结束 task_id=%s payload=%s", self.task_id, payload)
  128. self._send_report(payload, "结束上报(is_finished=1)")
  129. def _post_with_retry(self, url, payload, retries=REQUEST_RETRY_COUNT, timeout=REQUEST_TIMEOUT_SEC):
  130. last_err = None
  131. for attempt in range(1, retries + 1):
  132. try:
  133. resp = requests.post(
  134. url,
  135. headers=headers,
  136. data=payload,
  137. timeout=timeout,
  138. )
  139. resp.raise_for_status()
  140. return resp
  141. except Exception as e:
  142. last_err = e
  143. if attempt < retries:
  144. logger.warning("请求失败,第%s/%s次重试: %s", attempt, retries, e)
  145. time.sleep(min(2 * attempt, 5))
  146. else:
  147. logger.error("请求失败,已达最大重试次数(%s): %s", retries, e)
  148. raise last_err
  149. def get_product_data(self):
  150. self.task_id = self.task_dict["id"]
  151. self.company_id = self.task_dict["company_id"]
  152. self.product = self.task_dict["product_name"]
  153. self.product_desc = self.task_dict.get("product_specs", "")
  154. self.brand = self.task_dict.get("product_brand", "")
  155. self.product_keyword = self.task_dict.get("product_keyword", "")
  156. self.collect_task_id = self.task_dict.get("collect_task_id", "")
  157. self.sampling_cycle = self.task_dict.get("sampling_cycle", "")
  158. self.sampling_start_time = self.task_dict.get("sampling_start_time", "")
  159. self.sampling_end_time = self.task_dict.get("sampling_end_time", "")
  160. self.collect_equipment_id = self.task_dict.get("collect_equipment_id", "")
  161. self.account_id = self.task_dict.get("collect_equipment_account_id", "")
  162. self.collect_region_id = self.task_dict.get("collect_region_id", "")
  163. self.collect_round = self.task_dict.get("collect_round", 1)
  164. @staticmethod
  165. def _timestamp_ms() -> str:
  166. return str(int(time.time() * 1000))
  167. def _list_payload(self, keyword, page):
  168. return {
  169. "traderName": "yaoex_pc",
  170. "trader": "pc",
  171. "closesignature": "yes",
  172. "signature_method": "md5",
  173. "signature": "****",
  174. "timestamp": self._timestamp_ms(),
  175. "token": self.token,
  176. "userToken": self.token,
  177. "userId": self.user_id,
  178. "roleId": "101",
  179. "userType": "下游客户",
  180. "buyerCode": self.user_id,
  181. "nowPage": str(page),
  182. "per": "20",
  183. "keyword": keyword,
  184. "catSearchId": "",
  185. "specs": "",
  186. "factoryIds": "",
  187. "sellerCodes": "",
  188. "sellerFilterMode": "0",
  189. "sortColumn": "default",
  190. "sortMode": "default",
  191. "ver": "1",
  192. "stock_mode": "1",
  193. "showExtendCard": "true",
  194. "needDinnerPrice": "true",
  195. "limitStart": "",
  196. "limitEnd": "",
  197. "deadLineStart": "",
  198. "deadLineEnd": "",
  199. "filterDtos": "",
  200. "showWholePurchase": "true",
  201. }
  202. def _detail_payload(self, spu_code, seller_code):
  203. return {
  204. "traderName": "yaoex_pc",
  205. "trader": "pc",
  206. "closesignature": "yes",
  207. "signature_method": "md5",
  208. "signature": "****",
  209. "timestamp": self._timestamp_ms(),
  210. "token": self.token,
  211. "userToken": self.token,
  212. "spuCode": str(spu_code),
  213. "sellerCode": str(seller_code),
  214. }
  215. def _shop_payload(self, enterprise_id):
  216. return {
  217. 'traderName': 'yaoex_pc',
  218. 'trader': 'pc',
  219. 'closesignature': 'yes',
  220. 'signature_method': 'md5',
  221. 'signature': '****',
  222. 'timestamp': self._timestamp_ms(),
  223. 'token': TOKEN,
  224. 'userToken': TOKEN,
  225. 'enterpriseId': enterprise_id,
  226. }
  227. def fetch_list_page(self, keyword, page):
  228. payload = self._list_payload(keyword, page)
  229. list_url = "https://gateway-b2b.fangkuaiyi.com/home/search/homeSearchList"
  230. resp = self._post_with_retry(list_url, payload)
  231. data = resp.json()
  232. recall_status = data.get("data", {}).get("recallStatus", 0)
  233. data_block = data.get("data", {}) or {}
  234. # 尝试提取总页数(常见字段名依次尝试)
  235. total_pages = 0
  236. for key in ("totalPage", "totalPages", "pageCount", "total", "totalCount", "totalNum", "totalSize"):
  237. val = data_block.get(key)
  238. if val is not None and int(val) > 0:
  239. total_pages = int(val)
  240. break
  241. if total_pages:
  242. logger.info("📊 列表 API 检测到总页数:%s (page=%s)", total_pages, page)
  243. else:
  244. logger.debug("列表 API 未返回总页数字段,data keys: %s", list(data_block.keys())[:20])
  245. if int(recall_status) == 1:
  246. return data_block.get("shopProducts", []) or [], total_pages
  247. else:
  248. return [], 0
  249. def fetch_detail(self, spu_code, seller_code):
  250. payload = self._detail_payload(spu_code, seller_code)
  251. detail_url = "https://gateway-b2b.fangkuaiyi.com/product/detail"
  252. resp = self._post_with_retry(detail_url, payload)
  253. return resp.json().get("data", {}) or {}
  254. def fetch_shop(self, seller_code):
  255. payload = self._shop_payload(seller_code)
  256. detail_url = 'https://gateway-b2b.fangkuaiyi.com/ycapp/shop/enterpriseQualification'
  257. resp = self._post_with_retry(detail_url, payload)
  258. shop_res = resp.json().get("data", {})
  259. base_info = shop_res.get("baseInfo", {})
  260. address = base_info.get("address", "")
  261. company_name = base_info.get("enterpriseName", "")
  262. return address, company_name
  263. def parse_product(self, item):
  264. seller_code = item.get("sellerCode")
  265. spu_code = item.get("spuCode")
  266. name_part = (item.get("productName") or "").strip()
  267. short_part = (item.get("shortName") or "").strip()
  268. product_name = f"{name_part} {short_part}".strip()
  269. shop_url = f"https://mall.yaoex.com/v2/store/#/detail/{seller_code}/home"
  270. # 这里读取数据库,获取城市
  271. company_adress, company_name = self.fetch_shop(seller_code)
  272. detail_json = self.fetch_detail(spu_code, seller_code)
  273. address = detail_json.get("enterpriseIntroduce", {}).get("address", "")
  274. city_id = province_id = city = province = ""
  275. if address:
  276. city_id, province_id, city, province = get_city(address.split("市")[0])
  277. raw_price = item.get("price")
  278. price = self.decrypt_price(raw_price)
  279. hash_text = f"{seller_code}_{spu_code}_{price}"
  280. item_id = hashlib.md5(hash_text.encode('utf-8')).hexdigest()
  281. is_sold_out = 0
  282. is_sold_out_text = item.get("statusDescription", "")
  283. if "商品已售罄" in is_sold_out_text:
  284. is_sold_out= 1
  285. shop_name = item.get("storeName")
  286. if not shop_name:
  287. shop_name = item.get("shopName")
  288. anonymous_store_name = ""
  289. if shop_name == "预约配送中心":
  290. anonymous_store_name = item.get("supplyName", "")
  291. inventory = item.get("currentInventory")
  292. if not inventory:
  293. inventory = item.get("stockCount")
  294. now = time.strftime("%Y-%m-%d %H:%M:%S")
  295. # 字段与 yaofangwang_crawl 中 product 对齐(供 DrugPipeline)
  296. product = {
  297. "platform": self.platform,
  298. "item_id": item_id,
  299. "enterprise_id": self.company_id,
  300. "product_name": product_name,
  301. "spec": item.get("spec"),
  302. "one_price": "",
  303. "detail_url": f"https://mall.yaoex.com/v2/product/#/spuCode/{spu_code}/sellerCode/{seller_code}",
  304. "shop_name": shop_name,
  305. "anonymous_store_name": anonymous_store_name,
  306. "shop_url": shop_url,
  307. "city_name": city,
  308. "city_id": city_id,
  309. "province_name": province,
  310. "province_id": province_id,
  311. "shipment_city_name": "",
  312. "shipment_city_id": "",
  313. "shipment_province_name": "",
  314. "shipment_province_id": "",
  315. "area_info": company_adress if company_adress else address,
  316. "factory_name": item.get("factoryName"),
  317. "scrape_date": time.strftime("%Y-%m-%d"),
  318. "price": price,
  319. "sales": "",
  320. "stock_count": inventory,
  321. "snapshot_url": "",
  322. "approval_num": item.get("approvalNum"),
  323. "produced_time": item.get("productionTime"),
  324. "deadline": item.get("deadLine"),
  325. "update_time": now,
  326. "insert_time": now,
  327. "number": 1,
  328. "product_brand": self.brand or "",
  329. "collect_task_id": self.collect_task_id,
  330. "search_name": self.product,
  331. "company_name": company_name,
  332. "collect_config_info": json.dumps(
  333. {
  334. "sampling_cycle": self.sampling_cycle,
  335. "sampling_start_time": self.sampling_start_time,
  336. "sampling_end_time": self.sampling_end_time,
  337. }
  338. ),
  339. "account_id": self.account_id,
  340. "collect_region_id": self.collect_region_id,
  341. "collect_round": self.collect_round,
  342. "is_sold_out": is_sold_out
  343. }
  344. return product
  345. def decrypt_price(self, ciphertext_b64):
  346. if not ciphertext_b64 or not str(ciphertext_b64).strip():
  347. return ""
  348. _KEY_FIXED = "GDLSAUO1KUMIIBCE"
  349. if not self.user_id:
  350. key = _KEY_FIXED.encode("utf-8")
  351. else:
  352. uid = str(self.user_id)[:6].rjust(6, "0")
  353. key = (_KEY_FIXED[:10] + uid).encode("utf-8")
  354. raw = base64.b64decode(ciphertext_b64.strip())
  355. cipher = AES.new(key, AES.MODE_ECB)
  356. plain = unpad(cipher.decrypt(raw), AES.block_size)
  357. price = plain.decode("utf-8")
  358. return price
  359. def search_data(self):
  360. keyword = self.product
  361. if self.brand:
  362. keyword = self.brand + " " + self.product
  363. if self.product_desc:
  364. keyword = keyword + " " + self.product_desc
  365. for page in range(1, 100):
  366. if self.scheduler.end:
  367. logger.warning("收到停止信号,终止采集")
  368. break
  369. logger.info("正在爬取%s %s,第%s页数据", self.brand, self.product, page)
  370. page_items, api_total_pages = self.fetch_list_page(keyword=keyword, page=page)
  371. if not page_items:
  372. break
  373. for item in page_items:
  374. if not item.get("productId") and item.get("groupBuyProductDto"):
  375. item = item.get("groupBuyProductDto") or {}
  376. name_part = (item.get("productName") or "").strip()
  377. short_part = (item.get("shortName") or "").strip()
  378. product_name = f"{name_part} {short_part}".strip()
  379. if self.product not in product_name:
  380. self.is_not_product += 1
  381. continue
  382. if self.brand not in product_name:
  383. self.is_not_product += 1
  384. continue
  385. self.is_not_product = 0
  386. product = self.parse_product(item)
  387. if not product.get("item_id"):
  388. continue
  389. logger.info(f"爬取到数据{json.dumps(product,ensure_ascii=False)}")
  390. try:
  391. self.pipeline.storge_data(product)
  392. logger.info("%s", json.dumps(product, ensure_ascii=False))
  393. except Exception as e:
  394. logger.exception("写入数据库失败: %s", e)
  395. time.sleep(random.randint(1, 3))
  396. if self.is_not_product > 15:
  397. break
  398. # 每页结束上报进度,检查限额
  399. self._page_no = page
  400. prog_status = self._report_progress(page, total_pages=api_total_pages)
  401. if prog_status == "limit_reached":
  402. logger.warning("⛔ 进度上报检测到限额,通知停止")
  403. self.scheduler.set_flag(True)
  404. time.sleep(random.randint(2, 5))
  405. def run(self):
  406. self._page_no = 0
  407. try:
  408. self.scheduler.start()
  409. self._report_start()
  410. self.search_data()
  411. except Exception as e:
  412. logger.error(e)
  413. self.is_success = False
  414. finally:
  415. self.scheduler.stop()
  416. try:
  417. self._report_end(
  418. success=self.is_success,
  419. real_count=self.pipeline.crawl_count,
  420. page_no=self._page_no,
  421. )
  422. except Exception:
  423. pass
  424. logger.info(f"爬取总数{self.pipeline.crawl_count}")
  425. return self.pipeline.crawl_count, self.is_success