3
0

yaoex_crawl.py 18 KB

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