ysb_snapshot_crawl.py 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903
  1. import base64
  2. import hashlib
  3. import json
  4. import math
  5. import random
  6. import re
  7. import signal
  8. import socket
  9. import sys
  10. import time
  11. import zlib
  12. from pathlib import Path
  13. import requests
  14. import secrets
  15. import string
  16. from Crypto.Cipher import AES
  17. from commons.conn_mysql import MySQLPoolOn2
  18. from DrissionPage import ChromiumPage, ChromiumOptions
  19. from commons.Logger import logger
  20. from oss_upload.oss_upload import AliyunOSSUploader
  21. from pipelines.drug_pipelines import DrugPipeline
  22. from datetime import datetime, timedelta
  23. from area_info.city_name_to_id import get_city
  24. import platform
  25. CAPTCHA_TOKEN = "zPzmt1mG1ouCU6GTzsZN2Lmm8pdZypapPcLJTBRETco"
  26. CAPTCHA_API_URL = "http://api.jfbym.com/api/YmServer/customApi"
  27. SLIDER_OFFSET_FIX = 10
  28. DETAIL_GET_TIMEOUT = 15
  29. DETAIL_URL_WAIT = 10
  30. DETAIL_DOM_WAIT = 8
  31. DETAIL_NAV_RETRIES = 3
  32. DETAIL_APPROVAL_XPATH = (
  33. 'xpath://div[@class="drug-info"]//span[contains(text(),"批准文号")]'
  34. )
  35. chrome_path = r"C:\Program Files\Google\Chrome\Application\chrome.exe"
  36. PROJECT_ROOT = Path(__file__).resolve().parents[2]
  37. YSB_SPIDER_DIR = PROJECT_ROOT / "spiders" / "yaoshibang"
  38. headers = {
  39. "Accept": "*/*",
  40. "Accept-Language": "zh-CN,zh;q=0.9",
  41. "Connection": "keep-alive",
  42. "Content-Type": "application/json",
  43. "Origin": "https://dian.ysbang.cn",
  44. "Referer": "https://dian.ysbang.cn/",
  45. "Sec-Fetch-Dest": "empty",
  46. "Sec-Fetch-Mode": "cors",
  47. "Sec-Fetch-Site": "same-origin",
  48. "User-Agent": (
  49. "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 "
  50. "(KHTML, like Gecko) Chrome/146.0.0.0 Safari/537.36"
  51. ),
  52. "sec-ch-ua": '"Chromium";v="146", "Not-A.Brand";v="24", "Google Chrome";v="146"',
  53. "sec-ch-ua-mobile": "?0",
  54. "sec-ch-ua-platform": '"Windows"',
  55. }
  56. def pkcs7_unpad(data):
  57. if not data:
  58. raise ValueError("Empty data for PKCS7 unpad")
  59. pad_len = data[-1]
  60. if pad_len < 1 or pad_len > 16:
  61. raise ValueError("Invalid PKCS7 padding length")
  62. if data[-pad_len:] != bytes([pad_len]) * pad_len:
  63. raise ValueError("Invalid PKCS7 padding bytes")
  64. return data[:-pad_len]
  65. def derive_ysb_key():
  66. base = "BhCLxFfFhd12K4qRGPfy"
  67. md5_hex = hashlib.md5(base.encode("utf-8")).hexdigest()
  68. return md5_hex[:16].upper().encode("utf-8")
  69. def decrypt_ysb_payload(cipher_text_b64):
  70. """解密药师帮列表接口 data.o 字段,返回 JSON 对象。"""
  71. key = derive_ysb_key()
  72. cipher_bytes = base64.b64decode(cipher_text_b64)
  73. cipher = AES.new(key, AES.MODE_ECB)
  74. decrypted = cipher.decrypt(cipher_bytes)
  75. unpadded = pkcs7_unpad(decrypted)
  76. json_bytes = zlib.decompress(unpadded, zlib.MAX_WBITS | 16)
  77. return json.loads(json_bytes.decode("utf-8"))
  78. class YaoShiBangSnapshot:
  79. def __init__(self, drug_dict=None):
  80. self.driver = None
  81. self.db = MySQLPoolOn2()
  82. self.ip = None
  83. self.login_username = None
  84. self.login_password = None
  85. self.platform = 5
  86. self.page = 0
  87. self.pipeline = DrugPipeline("ysb")
  88. self.task_dict = drug_dict or {}
  89. self.ossuploader = AliyunOSSUploader()
  90. self.start_page = 1
  91. self.end_page = 1
  92. self.account_name = None
  93. self.phone = None
  94. self.password = None
  95. self._register_signal_handler()
  96. if self.task_dict:
  97. self.get_product_data()
  98. self.success = True
  99. self.is_no_prodcut = 0
  100. self.is_product_count = 0
  101. self.token = ""
  102. self._state_value = ""
  103. self.start_date = (datetime.now() - timedelta(minutes=500)).strftime("%Y-%m-%d %H:%M")
  104. def get_product_data(self):
  105. self.task_id = self.task_dict["id"]
  106. self.company_id = self.task_dict["company_id"]
  107. self.product = self.task_dict["product_name"]
  108. self.product_desc = self.task_dict.get("product_specs", "")
  109. self.brand = self.task_dict.get("product_brand", "")
  110. self.product_keyword = self.task_dict.get("product_keyword", "")
  111. self.collect_task_id = self.task_dict.get("collect_task_id", "")
  112. self.sampling_cycle = self.task_dict.get("sampling_cycle", "")
  113. self.sampling_start_time = self.task_dict.get("sampling_start_time", "")
  114. self.sampling_end_time = self.task_dict.get("sampling_end_time", "")
  115. self.collect_equipment_id = self.task_dict.get("collect_equipment_id", "")
  116. self.account_id = self.task_dict.get("collect_equipment_account_id", "")
  117. self.collect_region_id = self.task_dict.get("collect_region_id", "")
  118. self.collect_round = self.task_dict.get("collect_round", 1)
  119. self.start_page = self._parse_page(self.task_dict.get("start_page"), 1)
  120. self.end_page = max(
  121. self.start_page,
  122. self._parse_page(self.task_dict.get("end_page"), self.start_page),
  123. )
  124. def _report_exception(self, exception_type, remark=""):
  125. scheduler = self.task_dict.get("scheduler")
  126. if scheduler:
  127. data = {
  128. "task_id": self.task_id,
  129. "platform": self.task_dict.get("_platform", str(self.platform)),
  130. "username": self.task_dict.get("_device_id", ""),
  131. "current_page": self.page,
  132. "is_finished": 0,
  133. "exception_type": exception_type,
  134. "remark": remark,
  135. }
  136. if self.page:
  137. data["total_pages"] = self.page
  138. if self.pipeline.crawl_count:
  139. data["crawled_count"] = self.pipeline.crawl_count
  140. scheduler.post_report(data)
  141. def _report_page_progress(self, page, crawled_count, is_finished=0, total_pages=0):
  142. """逐页回告进度,返回 True=code=error 需停止"""
  143. scheduler = self.task_dict.get("scheduler")
  144. if scheduler:
  145. data = {
  146. "task_id": self.task_id,
  147. "platform": self.task_dict.get("_platform", str(self.platform)),
  148. "username": self.task_dict.get("_device_id", ""),
  149. "current_page": page,
  150. "crawled_count": crawled_count,
  151. "is_finished": is_finished,
  152. }
  153. if total_pages:
  154. data["total_pages"] = total_pages
  155. scheduler.post_report(data)
  156. return scheduler.end
  157. return False
  158. @staticmethod
  159. def _parse_page(value, default=1):
  160. try:
  161. page = int(value)
  162. return page if page >= 1 else default
  163. except (TypeError, ValueError):
  164. return default
  165. def _register_signal_handler(self):
  166. def handler(signum, frame):
  167. logger.info("收到退出信号,正在关闭浏览器...")
  168. self._quit_browser()
  169. sys.exit(0)
  170. signal.signal(signal.SIGINT, handler)
  171. if hasattr(signal, "SIGTERM"):
  172. signal.signal(signal.SIGTERM, handler)
  173. def _quit_browser(self):
  174. if self.driver:
  175. try:
  176. self.driver.quit()
  177. except Exception:
  178. pass
  179. self.driver = None
  180. @staticmethod
  181. def _get_free_port():
  182. """获取一个当前可用的本地端口,供 Chrome 调试使用。"""
  183. with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
  184. s.bind(("127.0.0.1", 0))
  185. return s.getsockname()[1]
  186. def _resolve_browser_profile_dir(self):
  187. """浏览器数据目录: <项目根>/spiders/yaoshibang/<账号>"""
  188. profile_dir = YSB_SPIDER_DIR / self.account_name
  189. # 仅兼容历史误路径,新建不再使用 chrome_profile
  190. legacy_nested = YSB_SPIDER_DIR / "spiders" / "yaoshibang" / self.account_name
  191. legacy_chrome_profile = YSB_SPIDER_DIR / "chrome_profile" / self.account_name
  192. for candidate in (profile_dir, legacy_nested, legacy_chrome_profile):
  193. if (candidate / "Default").is_dir() or (candidate / "Local State").is_file():
  194. logger.info("使用已有浏览器配置目录: %s", candidate)
  195. return candidate
  196. profile_dir.mkdir(parents=True, exist_ok=True)
  197. logger.info("新建浏览器配置目录: %s", profile_dir)
  198. return profile_dir
  199. def get_account(self):
  200. # 优先用入口传入的账号密码,避免重复查 DB
  201. phone = self.task_dict.get("account_phone")
  202. password = self.task_dict.get("account_password")
  203. name = self.task_dict.get("account_name")
  204. if phone and password:
  205. self.account_name = name or phone
  206. self.phone = phone
  207. self.password = password
  208. logger.info("使用入口传入的账号: name=%s, phone=%s", self.account_name, phone)
  209. return {"name": self.account_name, "phone": phone, "password": password}
  210. # 兜底:查 DB
  211. sql_account = f""" select `id`,`name`,`ip`,`phone`,`password`,`cookie_timestamp`,`cookie_str` from `accounts_platform` where `platform`=5 and `status`=1 and `equipment_id`=3 order by `cookie_timestamp` asc limit 1 """
  212. account_list = self.db.select_data(sql_account)
  213. if not account_list:
  214. return {}
  215. account_dict = account_list[0]
  216. self.account_name = account_dict["name"]
  217. self.phone = account_dict["phone"]
  218. self.password = account_dict["password"]
  219. return account_dict
  220. def init_browser(self):
  221. co = ChromiumOptions()
  222. # ---------- 1. 根据系统选择 Chrome 路径 ----------
  223. system = platform.system()
  224. if system == "Windows":
  225. chrome_path = r"C:\Program Files\Google\Chrome\Application\chrome.exe"
  226. # 如果装在非默认路径,可再追加备选
  227. elif system == "Linux":
  228. chrome_path = "/usr/bin/google-chrome" # 或 "/usr/bin/chromium-browser"
  229. else: # macOS 或其他
  230. chrome_path = None # 让 DrissionPage 自动查找
  231. if chrome_path:
  232. co.set_browser_path(chrome_path)
  233. # ---------- 2. 统一使用 set_argument 设置(避免 set_headless 报错) ----------
  234. co.set_argument('--headless') # 旧版无头(更兼容)
  235. co.set_argument('--window-size=1920,1080')
  236. co.set_argument('--no-sandbox') # Linux 必需,Windows 下被忽略,无害
  237. co.set_argument('--disable-dev-shm-usage') # Linux 解决 /dev/shm 问题,Windows 无害
  238. co.set_argument('--disable-gpu') # 无头模式下可减少 GPU 问题,兼容所有系统
  239. co.set_argument('--disable-blink-features=AutomationControlled')
  240. co.set_argument('--start-maximized')
  241. co.set_argument('--no-first-run')
  242. co.set_argument('--no-default-browser-check')
  243. # ---------- 3. 用户数据目录(跨平台) ----------
  244. # 例如放在项目目录下的 profiles/ 中,按账号区分
  245. profile_dir = Path("./browser_profiles") / self.account_name
  246. profile_dir.mkdir(parents=True, exist_ok=True)
  247. co.set_user_data_path(str(profile_dir))
  248. co.set_argument("--remote-debugging-port=0")
  249. co.set_argument("--remote-debugging-address=127.0.0.1")
  250. self.driver = ChromiumPage(co)
  251. def _solve_slider_captcha(self):
  252. """检测并处理易盾滑块验证码,成功返回 True。"""
  253. self.driver.wait.doc_loaded()
  254. time.sleep(2)
  255. yidun = self.driver.ele("xpath://div[@class='yidun_modal']", timeout=3)
  256. if not yidun:
  257. return True
  258. logger.info("检测到滑块验证码,开始处理")
  259. jpg_bytes = yidun.get_screenshot(as_bytes="jpg")
  260. distance = self._call_captcha_api(jpg_bytes)
  261. if distance is None:
  262. logger.error("验证码识别失败")
  263. self._report_exception(3, "滑块验证码识别失败")
  264. return False
  265. logger.info("滑块距离: %s", distance)
  266. slider = self.driver.ele(
  267. "xpath://div[contains(@class,'yidun_slider--hover')]", timeout=5
  268. )
  269. if not slider:
  270. logger.error("未找到滑块元素")
  271. self._report_exception(3, "未找到滑块元素")
  272. return False
  273. try:
  274. drag_distance = float(distance) + SLIDER_OFFSET_FIX
  275. except (TypeError, ValueError):
  276. logger.error("滑块距离非数字: %r", distance)
  277. return False
  278. if not math.isfinite(drag_distance) or drag_distance <= 0:
  279. logger.error("滑块距离无效: %s", drag_distance)
  280. return False
  281. self._simulate_slider_drag(slider, drag_distance - 5)
  282. time.sleep(3)
  283. return True
  284. def _call_captcha_api(self, image_bytes):
  285. """调用云码平台识别滑块距离,失败返回 None。"""
  286. try:
  287. b64 = base64.b64encode(image_bytes).decode()
  288. resp = requests.post(
  289. CAPTCHA_API_URL,
  290. json={"token": CAPTCHA_TOKEN, "type": "22222", "image": b64},
  291. headers={"Content-Type": "application/json"},
  292. timeout=15,
  293. ).json()
  294. logger.info("验证码 API 返回: %s", resp)
  295. if not isinstance(resp, dict):
  296. return None
  297. data = resp.get("data")
  298. if isinstance(data, dict):
  299. dist = data.get("data")
  300. else:
  301. dist = data
  302. if dist is None:
  303. logger.error("验证码 API 未返回距离字段: %s", resp)
  304. return None
  305. try:
  306. d = float(dist)
  307. except (TypeError, ValueError):
  308. logger.error("验证码距离无法解析为数字: %r", dist)
  309. return None
  310. if not math.isfinite(d):
  311. logger.error("验证码距离非有限数值: %r", dist)
  312. return None
  313. return d
  314. except Exception as e:
  315. logger.exception("验证码 API 调用失败: %s", e)
  316. return None
  317. @staticmethod
  318. def _generate_human_track(distance):
  319. try:
  320. distance = float(distance)
  321. except (TypeError, ValueError):
  322. return []
  323. if distance <= 0 or not math.isfinite(distance):
  324. return []
  325. tracks = []
  326. current = 0
  327. mid = distance * 0.7
  328. t = 0.2
  329. v = 0
  330. move_points = []
  331. while current < mid:
  332. a = random.uniform(2, 4)
  333. v0 = v
  334. v = v0 + a * t
  335. move = v0 * t + 0.5 * a * t * t
  336. current += move
  337. move_points.append(move)
  338. while current < distance:
  339. a = -random.uniform(0.5, 1.5)
  340. v0 = v
  341. v = v0 + a * t
  342. if v < 0.5:
  343. v = 0.5
  344. move = v0 * t + 0.5 * a * t * t
  345. current += move
  346. move_points.append(move)
  347. total_points = len(move_points)
  348. for i, move in enumerate(move_points):
  349. y_offset = random.randint(-2, 2) if i % random.randint(2, 4) == 0 else 0
  350. if i < total_points * 0.3:
  351. duration = random.uniform(0.01, 0.03)
  352. elif i > total_points * 0.7:
  353. duration = random.uniform(0.03, 0.08)
  354. else:
  355. duration = random.uniform(0.02, 0.05)
  356. if random.random() < 0.05:
  357. duration += random.uniform(0.05, 0.1)
  358. tracks.append((move, y_offset, duration))
  359. if random.random() < 0.7:
  360. tracks.append((-random.randint(1, 3), 0, 0.05))
  361. return tracks
  362. def _simulate_slider_drag(self, slider_element, target_distance):
  363. if target_distance <= 0:
  364. logger.warning("滑块目标距离无效: %s", target_distance)
  365. return
  366. self.driver.actions.move_to(slider_element).hold()
  367. for offset_x, offset_y, duration in self._generate_human_track(target_distance):
  368. self.driver.actions.move(offset_x, offset_y, duration=duration / 1000)
  369. self.driver.actions.release()
  370. def _is_logged_in(self):
  371. # 与当前账号店铺展示文案一致;换店后需同步修改或改为配置项
  372. title = self.driver.ele(
  373. "xpath=//span[@class='logout']",
  374. timeout=5,
  375. )
  376. return bool(title)
  377. def _current_url(self):
  378. try:
  379. return self.driver.url or ""
  380. except Exception:
  381. return ""
  382. def _goto_detail_page(self, item_id, detail_url):
  383. """get 后 refresh 一次,让 SPA 按当前 URL 重新渲染详情。"""
  384. for attempt in range(1, DETAIL_NAV_RETRIES + 1):
  385. try:
  386. self.driver.get(detail_url, timeout=5)
  387. time.sleep(1.5)
  388. eles = self.driver.eles("xpath=//div[@class='y-dialog']//button[contains(text(),'确认')]", timeout=3)
  389. if len(eles) == 2:
  390. eles[1].click()
  391. time.sleep(1)
  392. self.driver.refresh()
  393. time.sleep(1.5)
  394. ele = self.driver.ele("xpath=//div[@class='drug-pic-viewer']")
  395. if not ele:
  396. continue
  397. else:
  398. return True
  399. except Exception as e:
  400. logger.warning(
  401. "跳转详情异常 item_id=%s attempt=%s: %s",
  402. item_id, attempt, e,
  403. )
  404. time.sleep(random.uniform(0.8, 1.5))
  405. return False
  406. def login(self):
  407. logger.info("开始登录药师帮")
  408. self.driver.get("https://dian.ysbang.cn/#/login", timeout=15)
  409. self.driver.wait.doc_loaded(timeout=10)
  410. time.sleep(2)
  411. input_name = self.driver.ele("xpath://input[@name='userAccount']", timeout=5)
  412. if not input_name:
  413. logger.error("未找到账号输入框")
  414. self._report_exception(4, "登录页未找到账号输入框")
  415. return False
  416. input_name.input(self.phone)
  417. time.sleep(random.uniform(1.5, 2.5))
  418. input_pass = self.driver.ele("xpath://input[@name='password']", timeout=5)
  419. if not input_pass:
  420. logger.error("未找到密码输入框")
  421. self._report_exception(4, "登录页未找到密码输入框")
  422. return False
  423. input_pass.input(self.password)
  424. time.sleep(random.uniform(1.5, 2.5))
  425. login_btn = self.driver.ele("xpath://button[text()='登录']", timeout=5)
  426. if not login_btn:
  427. logger.error("未找到登录按钮")
  428. self._report_exception(4, "登录页未找到登录按钮")
  429. return False
  430. login_btn.click()
  431. time.sleep(3)
  432. for i in range(3):
  433. self._solve_slider_captcha()
  434. time.sleep(3)
  435. if self._is_logged_in():
  436. logger.info("登录成功")
  437. return True
  438. logger.error("登录后未检测到目标店铺名,登录可能失败")
  439. return False
  440. def save_cookies(self, cookies_list):
  441. cookies_dict = {c['name']: c['value'] for c in cookies_list}
  442. timestamp = int(time.time())
  443. next_update_time = timestamp + random.randint(3600, 7200)
  444. update_sql = f""" UPDATE `accounts_platform` SET `cookie_timestamp` = %s, `cookie_str`= %s,`cookie_update_time` = %s, `status`= %s WHERE `name` = %s; """
  445. self.db.execute(update_sql,
  446. (timestamp, json.dumps(cookies_dict), next_update_time, 1, self.account_name))
  447. logger.info("cookie已保存成功")
  448. def _take_snapshot(self, upload_key):
  449. """在当前页面截图并上传,不再重复跳转。"""
  450. time.sleep(1)
  451. self._dismiss_popup_before_screenshot()
  452. try:
  453. jpg_bytes = self.driver.get_screenshot(as_bytes="jpg", full_page=True)
  454. if not jpg_bytes:
  455. logger.warning("截图为空 upload_key=%s", upload_key)
  456. return ""
  457. img_url = self.ossuploader.upload_from_bytes(jpg_bytes, str(upload_key))
  458. except Exception:
  459. logger.exception("截图或 OSS 上传失败 upload_key=%s", upload_key)
  460. return ""
  461. if not img_url:
  462. logger.warning("OSS 未返回有效地址 upload_key=%s", upload_key)
  463. return ""
  464. logger.info("截图上传完成 upload_key=%s url=%s", upload_key, img_url)
  465. time.sleep(random.uniform(1, 2))
  466. return img_url
  467. def gen_pair(self, ex1_len=9, o_raw_len=16):
  468. alphabet = string.ascii_lowercase + string.digits
  469. ex1 = "".join(secrets.choice(alphabet) for _ in range(ex1_len))
  470. o = base64.b64encode(secrets.token_bytes(o_raw_len)).decode("ascii")
  471. return {"ex1": ex1, "o": o}
  472. def build_base_payload(self, keyword, page, first_search):
  473. date_str = time.strftime("%Y-%m-%d %H:%M:%S")
  474. return {
  475. "platform": "pc",
  476. "version": "6.0.0",
  477. "ua": "Chrome146",
  478. 'ex': '{} drugInfo {} {}'.format(self.start_date, date_str, date_str),
  479. "trafficType": 1,
  480. "ex1": "",
  481. "o": "",
  482. "lastClick": -1,
  483. "page": page,
  484. "pagesize": "60",
  485. "classify_id": "",
  486. "searchkey": keyword,
  487. "onlyTcm": 0,
  488. "operationtype": 1,
  489. "qualifiedLoanee": 0,
  490. "drugId": -1,
  491. "tagId": "",
  492. "showRecentlyPurchasedFlag": True,
  493. "onlySimpleLoan": 0,
  494. "sn": "",
  495. "buttons": [],
  496. "buttonList": [],
  497. "synonymId": 0,
  498. "activityTypes": [],
  499. "provider_filter": "",
  500. "factoryNames": "",
  501. "tcmGradeNames": [],
  502. "tcmExeStandardIds": [],
  503. "specs": "",
  504. "deliverFloor": 0,
  505. "purchaseLimitFloor": 0,
  506. "nextRequestKey": "",
  507. "adConfigId": 0,
  508. "stateValue": self._state_value,
  509. "firstSearch": first_search,
  510. "token": self.token,
  511. }
  512. @staticmethod
  513. def _extract_state_value(json_data, data_block):
  514. for src in (json_data, data_block):
  515. if not isinstance(src, dict):
  516. continue
  517. val = src.get("stateValue") or src.get("state_value")
  518. if val:
  519. return str(val)
  520. return None
  521. def _dismiss_popup_before_screenshot(self):
  522. """截图前关闭或隐藏营销弹窗,避免遮挡。"""
  523. self.driver.run_js("""
  524. // 暴力清除所有高 z-index 遮罩和弹窗
  525. document.querySelectorAll('*').forEach(el => {
  526. const s = getComputedStyle(el);
  527. const z = parseInt(s.zIndex) || 0;
  528. if (z > 100 && (s.position === 'fixed' || s.position === 'absolute') &&
  529. (el.clientWidth > 100 || el.clientHeight > 100)) {
  530. el.remove();
  531. }
  532. });
  533. """)
  534. close_locs = [
  535. "xpath=//div[contains(@class,'dialog')]//i[contains(@class,'close')]",
  536. "xpath=//div[contains(@class,'popup')]//i[contains(@class,'close')]",
  537. "xpath=//div[contains(@class,'modal')]//i[contains(@class,'close')]",
  538. "xpath=//button[contains(@class,'close')]",
  539. "xpath=//span[text()='×']",
  540. "xpath=//*[contains(text(),'智能采购')]/ancestor::div[1]//*[contains(@class,'close')]",
  541. "xpath=//*[contains(text(),'智能采购')]/ancestor::div[3]//*[contains(@class,'close')]",
  542. "xpath=//*[contains(text(),'智能采购')]/ancestor::div[3]//button[last()]",
  543. ]
  544. for loc in close_locs:
  545. try:
  546. btn = self.driver.ele(loc, timeout=0.5)
  547. if btn:
  548. btn.click()
  549. time.sleep(0.2)
  550. except Exception:
  551. pass
  552. try:
  553. # 兜底:隐藏常见高层弹窗和遮罩
  554. self.driver.run_js(
  555. """
  556. const sels = [
  557. '[class*="modal"]',
  558. '[class*="popup"]',
  559. '[class*="dialog"]',
  560. '[class*="mask"]',
  561. '[class*="overlay"]'
  562. ];
  563. for (const s of sels) {
  564. document.querySelectorAll(s).forEach(el => {
  565. const style = getComputedStyle(el);
  566. const z = parseInt(style.zIndex || '0', 10);
  567. if (z >= 999 && style.display !== 'none') {
  568. el.style.display = 'none';
  569. }
  570. });
  571. }
  572. document.body.style.overflow = 'auto';
  573. """
  574. )
  575. time.sleep(0.2)
  576. except Exception:
  577. pass
  578. def to_product(self, item):
  579. now = time.strftime("%Y-%m-%d %H:%M:%S")
  580. item_id = item.get("wholesaleid", "")
  581. provider_id = item.get("providerId", "")
  582. city_str = item.get("warehouseCity", "")
  583. city_id = province_id = city = province = ""
  584. price = item.get("disPrice", "")
  585. if not price:
  586. price = item.get("minprice", "")
  587. if not price:
  588. price = item.get("price", "")
  589. shop_name = item.get("provider_name", "")
  590. if not shop_name:
  591. shop_name = item.get("abbreviation", "")
  592. # 销量: 优先 order_amount > orderAmountPlus > alreadysales
  593. sales = (
  594. item.get("order_amount")
  595. or item.get("orderAmountPlus")
  596. or item.get("alreadysales")
  597. or ""
  598. )
  599. product = {
  600. "platform": self.platform,
  601. "item_id": item_id,
  602. "enterprise_id": self.company_id,
  603. "product_name": item.get("drugname", ""),
  604. "spec": item.get("specification", ""),
  605. "one_price": '',
  606. "detail_url": f"https://dian.ysbang.cn/#/drugInfo?wholesaleid={item_id}&trafficType=1",
  607. "shop_name": shop_name,
  608. "anonymous_store_name": "",
  609. "shop_url": f"https://dian.ysbang.cn/#/supplierstore?providerId={provider_id}&trafficType=4",
  610. "city_name": city,
  611. "city_id": city_id,
  612. "province_name": province,
  613. "province_id": province_id,
  614. "area_info": "",
  615. "factory_name": item.get("manufacturer", ""),
  616. "scrape_date": time.strftime("%Y-%m-%d"),
  617. "price": price,
  618. "sales": sales,
  619. "stock_count": item.get("stockAvailable", ""),
  620. "snapshot_url": "",
  621. "approval_num": "",
  622. "produced_time": item.get("prodDate", ""),
  623. "deadline": item.get("valid_date", ""),
  624. "update_time": now,
  625. "insert_time": now,
  626. "number": 1,
  627. "product_brand": self.brand or "",
  628. "collect_task_id": self.collect_task_id,
  629. "search_name": self.product,
  630. "company_name": "",
  631. "collect_config_info": json.dumps(
  632. {"sampling_cycle": self.sampling_cycle, "sampling_start_time": self.sampling_start_time,
  633. "sampling_end_time": self.sampling_end_time}),
  634. "account_id": self.account_id,
  635. "collect_region_id": self.collect_region_id,
  636. "collect_round": self.collect_round,
  637. "is_sold_out": 0
  638. }
  639. return product
  640. def parse_detail(self, product):
  641. appvolnum_ele = self.driver.ele(
  642. 'xpath://div[@class="drug-info"]//span[contains(text(),"批准文号")]/following-sibling::span[1]')
  643. appvolnum_value = appvolnum_ele.text if appvolnum_ele else ""
  644. price = ""
  645. discount_ele = self.driver.ele(
  646. 'xpath://div[@class="sale-info-wrap"]//div[@class="tooltip-content"]',
  647. timeout=2,
  648. )
  649. discount_value = discount_ele.text if discount_ele else ""
  650. if not price and discount_value:
  651. price_re = re.search(r"¥([0-9.]+)", discount_value)
  652. if price_re:
  653. price = price_re.group(1).strip()
  654. current_ele = self.driver.ele(
  655. 'xpath://div[@class="sale-info-wrap"]//span[contains(@class,"current-price")]',
  656. timeout=3,
  657. )
  658. if current_ele and not price:
  659. price = (current_ele.text or "").replace("¥", "").strip()
  660. list_price = product.get("price", "")
  661. if price:
  662. product["price"] = price
  663. if appvolnum_value:
  664. product["approval_num"] = appvolnum_value
  665. logger.info(
  666. "详情解析 wholesaleid=%s list_price=%s dom_price=%s url=%s",
  667. product.get("item_id"),
  668. list_price,
  669. product.get("price"),
  670. self._current_url(),
  671. )
  672. return product
  673. def search(self):
  674. self.driver.get("https://dian.ysbang.cn/#/home", timeout=15)
  675. self.driver.wait.doc_loaded(timeout=10)
  676. time.sleep(2)
  677. if not self._is_logged_in():
  678. if not self.login():
  679. return False
  680. time.sleep(3)
  681. cookies_list = self.driver.cookies()
  682. cookies_dict = {c['name']: c['value'] for c in cookies_list}
  683. self.save_cookies(cookies_list)
  684. self.token = cookies_dict.get("Token") or cookies_dict.get("token")
  685. keyword = self.product
  686. if self.brand:
  687. keyword = (self.brand + " " + self.product).strip()
  688. if self.product_desc:
  689. keyword = (keyword + " " + self.product_desc).strip()
  690. self._state_value = ""
  691. # 支持续传:从 current_page(>0)或 start_page 开始
  692. page_start = int(self.task_dict.get("current_page", 0) or 0)
  693. if page_start <= 0:
  694. page_start = self.start_page
  695. self.page = page_start # 兜底:避免0页时回告 total_pages=0
  696. for page in range(page_start, 100):
  697. first_search = page == 1
  698. logger.info("药师帮爬取第%s页 firstSearch=%s stateValue=%s", page, first_search,
  699. self._state_value or "(空)")
  700. pair = self.gen_pair()
  701. payload = self.build_base_payload(keyword, page=page, first_search=first_search)
  702. payload["ex1"] = pair["ex1"]
  703. payload["o"] = pair["o"]
  704. response = None
  705. for attempt in range(3):
  706. try:
  707. response = requests.post(
  708. "https://dian.ysbang.cn/wholesale-drug/sales/getWholesaleList/v4270", headers=headers,
  709. json=payload, timeout=30
  710. )
  711. if response.status_code == 200:
  712. break
  713. except Exception as e:
  714. logger.error("第%s页请求失败 (%s/3): %s", page, attempt + 1, e)
  715. response = None
  716. time.sleep(10)
  717. if not response or response.status_code != 200:
  718. logger.error("第%s页请求失败,停止爬取", page)
  719. self._report_exception(5, f"第{page}页请求失败(status={response.status_code if response else 'None'})")
  720. return False
  721. try:
  722. data_json = response.json()
  723. except json.JSONDecodeError:
  724. logger.exception("第%s页响应不是合法 JSON", page)
  725. self._report_exception(5, f"第{page}页响应非合法JSON")
  726. return False
  727. data_block = data_json.get("data") or {}
  728. if str(data_json.get("message", "")) == "该操作需要登录":
  729. logger.warning("第%s页需要登录,请检查浏览器登录态", page)
  730. self._report_exception(1, "账号登录态失效")
  731. return False
  732. encrypted_o = data_block.get("o")
  733. if not encrypted_o:
  734. logger.warning("第%s页返回无加密 data.o: %s", page, data_json)
  735. break
  736. try:
  737. json_data = decrypt_ysb_payload(encrypted_o)
  738. except Exception as e:
  739. logger.exception("第%s页解密失败: %s", page, e)
  740. self._report_exception(6, f"第{page}页数据解密失败")
  741. continue
  742. state_val = self._extract_state_value(json_data, data_block)
  743. logger.info("第%s页 解密后 keys: %s, stateValue=%s, has_wholesales=%s", page,
  744. list(json_data.keys())[:20], state_val, bool(json_data.get("wholesales")))
  745. if state_val:
  746. self._state_value = state_val
  747. wholesales = json_data.get("wholesales", [])
  748. if not wholesales:
  749. logger.info(f"第{page}页无数据,停止")
  750. break
  751. for item in wholesales:
  752. item_id = item.get("wholesaleid", "")
  753. if not item_id:
  754. continue
  755. detail_url = (
  756. f"https://dian.ysbang.cn/#/drugInfo?wholesaleid={item_id}&trafficType=1"
  757. )
  758. product = self.to_product(item)
  759. title = product.get("product_name", "")
  760. if self.brand not in title:
  761. self.is_product_count += 1
  762. continue
  763. if self.product not in title:
  764. self.is_product_count += 1
  765. continue
  766. if self.product in title and self.brand in title:
  767. self.is_product_count = 0
  768. if self.is_product_count >= 20:
  769. return False
  770. if not self._goto_detail_page(item_id, detail_url):
  771. logger.warning(
  772. "详情页跳转失败,跳过 item_id=%s url=%s",
  773. item_id, detail_url,
  774. )
  775. continue
  776. product = self.parse_detail(product)
  777. upload_key = hashlib.md5(detail_url.encode("utf-8")).hexdigest()
  778. product["snapshot_url"] = self._take_snapshot(upload_key)
  779. try:
  780. self.pipeline.storge_data(product)
  781. logger.info("%s", json.dumps(product, ensure_ascii=False, default=str))
  782. except Exception as e:
  783. logger.exception("写入数据库失败: %s", e)
  784. # 逐页回告进度
  785. self.page = page
  786. if self._report_page_progress(page, self.pipeline.crawl_count) == True:
  787. break
  788. def run(self):
  789. account_dict = self.get_account()
  790. if not account_dict:
  791. logger.error("ysb快照模式无账号可用")
  792. self._report_exception(1, "无可用账号")
  793. return 0, False
  794. try:
  795. self.init_browser()
  796. self.search()
  797. except Exception as e:
  798. logger.exception("运行异常: %s", e)
  799. self.success = False
  800. self._report_exception(5, f"未知异常: {e}")
  801. finally:
  802. self._quit_browser()
  803. return self.pipeline.crawl_count, self.success, self.page