ysb_snapshot_crawl.py 32 KB

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