3
0

yaoex_crawl.py 18 KB

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