3
0

yaoex_crawl.py 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466
  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 = "18193030281"
  18. HEARTBEAT_INTERVAL_SECONDS = 60
  19. TASK_API_BASE = "http://120.24.26.108:8082/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 if success else 0,
  123. }
  124. logger.info("上报结束 task_id=%s payload=%s", self.task_id, payload)
  125. self._send_report(payload, "结束上报(is_finished=1)")
  126. def _post_with_retry(self, url, payload, retries=REQUEST_RETRY_COUNT, timeout=REQUEST_TIMEOUT_SEC):
  127. last_err = None
  128. for attempt in range(1, retries + 1):
  129. try:
  130. resp = requests.post(
  131. url,
  132. headers=headers,
  133. data=payload,
  134. timeout=timeout,
  135. )
  136. resp.raise_for_status()
  137. return resp
  138. except Exception as e:
  139. last_err = e
  140. if attempt < retries:
  141. logger.warning("请求失败,第%s/%s次重试: %s", attempt, retries, e)
  142. time.sleep(min(2 * attempt, 5))
  143. else:
  144. logger.error("请求失败,已达最大重试次数(%s): %s", retries, e)
  145. raise last_err
  146. def get_product_data(self):
  147. self.task_id = self.task_dict["id"]
  148. self.company_id = self.task_dict["company_id"]
  149. self.product = self.task_dict["product_name"]
  150. self.product_desc = self.task_dict.get("product_specs", "")
  151. self.brand = self.task_dict.get("product_brand", "")
  152. self.product_keyword = self.task_dict.get("product_keyword", "")
  153. self.collect_task_id = self.task_dict.get("collect_task_id", "")
  154. self.sampling_cycle = self.task_dict.get("sampling_cycle", "")
  155. self.sampling_start_time = self.task_dict.get("sampling_start_time", "")
  156. self.sampling_end_time = self.task_dict.get("sampling_end_time", "")
  157. self.collect_equipment_id = self.task_dict.get("collect_equipment_id", "")
  158. self.account_id = self.task_dict.get("collect_equipment_account_id", "")
  159. self.collect_region_id = self.task_dict.get("collect_region_id", "")
  160. self.collect_round = self.task_dict.get("collect_round", 1)
  161. @staticmethod
  162. def _timestamp_ms() -> str:
  163. return str(int(time.time() * 1000))
  164. def _list_payload(self, keyword, page):
  165. return {
  166. "traderName": "yaoex_pc",
  167. "trader": "pc",
  168. "closesignature": "yes",
  169. "signature_method": "md5",
  170. "signature": "****",
  171. "timestamp": self._timestamp_ms(),
  172. "token": self.token,
  173. "userToken": self.token,
  174. "userId": self.user_id,
  175. "roleId": "101",
  176. "userType": "下游客户",
  177. "buyerCode": self.user_id,
  178. "nowPage": str(page),
  179. "per": "20",
  180. "keyword": keyword,
  181. "catSearchId": "",
  182. "specs": "",
  183. "factoryIds": "",
  184. "sellerCodes": "",
  185. "sellerFilterMode": "0",
  186. "sortColumn": "default",
  187. "sortMode": "default",
  188. "ver": "1",
  189. "stock_mode": "1",
  190. "showExtendCard": "true",
  191. "needDinnerPrice": "true",
  192. "limitStart": "",
  193. "limitEnd": "",
  194. "deadLineStart": "",
  195. "deadLineEnd": "",
  196. "filterDtos": "",
  197. "showWholePurchase": "true",
  198. }
  199. def _detail_payload(self, spu_code, seller_code):
  200. return {
  201. "traderName": "yaoex_pc",
  202. "trader": "pc",
  203. "closesignature": "yes",
  204. "signature_method": "md5",
  205. "signature": "****",
  206. "timestamp": self._timestamp_ms(),
  207. "token": self.token,
  208. "userToken": self.token,
  209. "spuCode": str(spu_code),
  210. "sellerCode": str(seller_code),
  211. }
  212. def _shop_payload(self, enterprise_id):
  213. return {
  214. 'traderName': 'yaoex_pc',
  215. 'trader': 'pc',
  216. 'closesignature': 'yes',
  217. 'signature_method': 'md5',
  218. 'signature': '****',
  219. 'timestamp': self._timestamp_ms(),
  220. 'token': TOKEN,
  221. 'userToken': TOKEN,
  222. 'enterpriseId': enterprise_id,
  223. }
  224. def fetch_list_page(self, keyword, page):
  225. payload = self._list_payload(keyword, page)
  226. list_url = "https://gateway-b2b.fangkuaiyi.com/home/search/homeSearchList"
  227. resp = self._post_with_retry(list_url, payload)
  228. data = resp.json()
  229. recall_status = data.get("data", {}).get("recallStatus", 0)
  230. data_block = data.get("data", {}) or {}
  231. # 尝试提取总页数(常见字段名依次尝试)
  232. total_pages = 0
  233. for key in ("totalPage", "totalPages", "pageCount", "total", "totalCount", "totalNum", "totalSize"):
  234. val = data_block.get(key)
  235. if val is not None and int(val) > 0:
  236. total_pages = int(val)
  237. break
  238. if total_pages:
  239. logger.info("📊 列表 API 检测到总页数:%s (page=%s)", total_pages, page)
  240. else:
  241. logger.debug("列表 API 未返回总页数字段,data keys: %s", list(data_block.keys())[:20])
  242. if int(recall_status) == 1:
  243. return data_block.get("shopProducts", []) or [], total_pages
  244. else:
  245. return [], 0
  246. def fetch_detail(self, spu_code, seller_code):
  247. payload = self._detail_payload(spu_code, seller_code)
  248. detail_url = "https://gateway-b2b.fangkuaiyi.com/product/detail"
  249. resp = self._post_with_retry(detail_url, payload)
  250. return resp.json().get("data", {}) or {}
  251. def fetch_shop(self, seller_code):
  252. payload = self._shop_payload(seller_code)
  253. detail_url = 'https://gateway-b2b.fangkuaiyi.com/ycapp/shop/enterpriseQualification'
  254. resp = self._post_with_retry(detail_url, payload)
  255. shop_res = resp.json().get("data", {})
  256. base_info = shop_res.get("baseInfo", {})
  257. address = base_info.get("address", "")
  258. company_name = base_info.get("enterpriseName", "")
  259. return address, company_name
  260. def parse_product(self, item):
  261. seller_code = item.get("sellerCode")
  262. spu_code = item.get("spuCode")
  263. name_part = (item.get("productName") or "").strip()
  264. short_part = (item.get("shortName") or "").strip()
  265. product_name = f"{name_part} {short_part}".strip()
  266. shop_url = f"https://mall.yaoex.com/v2/store/#/detail/{seller_code}/home"
  267. # 这里读取数据库,获取城市
  268. company_adress, company_name = self.fetch_shop(seller_code)
  269. detail_json = self.fetch_detail(spu_code, seller_code)
  270. address = detail_json.get("enterpriseIntroduce", {}).get("address", "")
  271. city_id = province_id = city = province = ""
  272. if address:
  273. city_id, province_id, city, province = get_city(address.split("市")[0])
  274. raw_price = item.get("price")
  275. price = self.decrypt_price(raw_price)
  276. hash_text = f"{seller_code}_{spu_code}_{price}"
  277. item_id = hashlib.md5(hash_text.encode('utf-8')).hexdigest()
  278. is_sold_out = 0
  279. is_sold_out_text = item.get("statusDescription", "")
  280. if "商品已售罄" in is_sold_out_text:
  281. is_sold_out= 1
  282. shop_name = item.get("storeName")
  283. if not shop_name:
  284. shop_name = item.get("shopName")
  285. anonymous_store_name = ""
  286. if shop_name == "预约配送中心":
  287. anonymous_store_name = item.get("supplyName", "")
  288. inventory = item.get("currentInventory")
  289. if not inventory:
  290. inventory = item.get("stockCount")
  291. now = time.strftime("%Y-%m-%d %H:%M:%S")
  292. # 字段与 yaofangwang_crawl 中 product 对齐(供 DrugPipeline)
  293. product = {
  294. "platform": self.platform,
  295. "item_id": item_id,
  296. "enterprise_id": self.company_id,
  297. "product_name": product_name,
  298. "spec": item.get("spec"),
  299. "one_price": "",
  300. "detail_url": f"https://mall.yaoex.com/v2/product/#/spuCode/{spu_code}/sellerCode/{seller_code}",
  301. "shop_name": shop_name,
  302. "anonymous_store_name": anonymous_store_name,
  303. "shop_url": shop_url,
  304. "city_name": city,
  305. "city_id": city_id,
  306. "province_name": province,
  307. "province_id": province_id,
  308. "shipment_city_name": "",
  309. "shipment_city_id": "",
  310. "shipment_province_name": "",
  311. "shipment_province_id": "",
  312. "area_info": company_adress if company_adress else address,
  313. "factory_name": item.get("factoryName"),
  314. "scrape_date": time.strftime("%Y-%m-%d"),
  315. "price": price,
  316. "sales": "",
  317. "stock_count": inventory,
  318. "snapshot_url": "",
  319. "approval_num": item.get("approvalNum"),
  320. "produced_time": item.get("productionTime"),
  321. "deadline": item.get("deadLine"),
  322. "update_time": now,
  323. "insert_time": now,
  324. "number": 1,
  325. "product_brand": self.brand or "",
  326. "collect_task_id": self.collect_task_id,
  327. "search_name": self.product,
  328. "company_name": company_name,
  329. "collect_config_info": json.dumps(
  330. {
  331. "sampling_cycle": self.sampling_cycle,
  332. "sampling_start_time": self.sampling_start_time,
  333. "sampling_end_time": self.sampling_end_time,
  334. }
  335. ),
  336. "account_id": self.account_id,
  337. "collect_region_id": self.collect_region_id,
  338. "collect_round": self.collect_round,
  339. "is_sold_out": is_sold_out
  340. }
  341. return product
  342. def decrypt_price(self, ciphertext_b64):
  343. if not ciphertext_b64 or not str(ciphertext_b64).strip():
  344. return ""
  345. _KEY_FIXED = "GDLSAUO1KUMIIBCE"
  346. if not self.user_id:
  347. key = _KEY_FIXED.encode("utf-8")
  348. else:
  349. uid = str(self.user_id)[:6].rjust(6, "0")
  350. key = (_KEY_FIXED[:10] + uid).encode("utf-8")
  351. raw = base64.b64decode(ciphertext_b64.strip())
  352. cipher = AES.new(key, AES.MODE_ECB)
  353. plain = unpad(cipher.decrypt(raw), AES.block_size)
  354. price = plain.decode("utf-8")
  355. return price
  356. def search_data(self):
  357. keyword = self.product
  358. if self.brand:
  359. keyword = self.brand + " " + self.product
  360. if self.product_desc:
  361. keyword = keyword + " " + self.product_desc
  362. for page in range(1, 100):
  363. if self.scheduler.end:
  364. logger.warning("收到停止信号,终止采集")
  365. break
  366. logger.info("正在爬取%s %s,第%s页数据", self.brand, self.product, page)
  367. page_items, api_total_pages = self.fetch_list_page(keyword=keyword, page=page)
  368. if not page_items:
  369. break
  370. for item in page_items:
  371. if not item.get("productId") and item.get("groupBuyProductDto"):
  372. item = item.get("groupBuyProductDto") or {}
  373. name_part = (item.get("productName") or "").strip()
  374. short_part = (item.get("shortName") or "").strip()
  375. product_name = f"{name_part} {short_part}".strip()
  376. if self.product not in product_name:
  377. self.is_not_product += 1
  378. continue
  379. if self.brand not in product_name:
  380. self.is_not_product += 1
  381. continue
  382. self.is_not_product = 0
  383. product = self.parse_product(item)
  384. if not product.get("item_id"):
  385. continue
  386. logger.info(f"爬取到数据{json.dumps(product,ensure_ascii=False)}")
  387. try:
  388. self.pipeline.storge_data(product)
  389. logger.info("%s", json.dumps(product, ensure_ascii=False))
  390. except Exception as e:
  391. logger.exception("写入数据库失败: %s", e)
  392. time.sleep(random.randint(1, 3))
  393. if self.is_not_product > 15:
  394. break
  395. # 每页结束上报进度,检查限额
  396. self._page_no = page
  397. prog_status = self._report_progress(page, total_pages=api_total_pages)
  398. if prog_status == "limit_reached":
  399. logger.warning("⛔ 进度上报检测到限额,通知停止")
  400. self.scheduler.set_flag(True)
  401. time.sleep(random.randint(2, 5))
  402. def run(self):
  403. self._page_no = 0
  404. try:
  405. self.scheduler.start()
  406. self._report_start()
  407. self.search_data()
  408. except Exception as e:
  409. logger.error(e)
  410. self.is_success = False
  411. finally:
  412. self.scheduler.stop()
  413. try:
  414. self._report_end(
  415. success=self.is_success,
  416. real_count=self.pipeline.crawl_count,
  417. page_no=self._page_no,
  418. )
  419. except Exception:
  420. pass
  421. logger.info(f"爬取总数{self.pipeline.crawl_count}")
  422. return self.pipeline.crawl_count, self.is_success