yaoex_crawl.py 15 KB

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