count_nums.py 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524
  1. from playwright.sync_api import sync_playwright, TimeoutError as PlaywrightTimeoutError
  2. import os
  3. import json
  4. import random
  5. from logger_config import logger
  6. from config import *
  7. import re
  8. COOKIE_FILE_PATH = "ybm_cookies.json" # Cookie保存路径
  9. LOGIN_VALIDATE_URL = "https://www.ybm100.com/new/"
  10. TARGET_LOGIN_URL = "https://www.ybm100.com/new/login"
  11. def load_cookies(context, cookie_path=COOKIE_FILE_PATH):
  12. """从本地JSON文件加载Cookie到浏览器上下文"""
  13. if not os.path.exists(cookie_path):
  14. # logger.warning(f" Cookie文件不存在:{cookie_path}")
  15. return False
  16. try:
  17. with open(cookie_path, "r", encoding="utf-8") as f:
  18. cookies = json.load(f)
  19. context.add_cookies(cookies)
  20. # logger.info(f"✅ 已从{cookie_path}加载Cookie")
  21. return True
  22. except Exception as e:
  23. # logger.error(f" 加载Cookie失败:{e}")
  24. return False
  25. def is_login(page):
  26. """验证是否已登录(核心:检测登录态)"""
  27. try:
  28. # 访问需要登录的页面
  29. page.goto(LOGIN_VALIDATE_URL, timeout=5000)
  30. page.wait_for_load_state("networkidle")
  31. # 检测是否跳转到登录页(URL包含login则未登录)
  32. if "login" in page.url.lower():
  33. # logger.warning(" Cookie失效,需要重新登录")
  34. return False
  35. # 可选:检测登录后的专属元素(比如用户名、个人中心等)
  36. # if page.locator("用户中心选择器").count() > 0:
  37. # return True
  38. # logger.info(" Cookie有效,已保持登录状态")
  39. return True
  40. except Exception as e:
  41. # logger.error(f" 验证登录状态失败:{e}")
  42. return False
  43. def popup_guard(page, tag=""):
  44. """
  45. 全局弹窗/遮罩守卫:多步引导 + 关闭按钮 + 遮罩清理 + 恢复滚动
  46. tag 仅用于日志区分调用位置
  47. """
  48. try:
  49. # 给弹窗一点出现时间
  50. page.wait_for_timeout(300)
  51. # 1) 连续点“下一步/完成/我知道了/关闭”
  52. for _ in range(6):
  53. btn = page.locator(
  54. "xpath=//button[normalize-space()='下一步' or normalize-space()='完成' or normalize-space()='我知道了' or normalize-space()='关闭']"
  55. ).first
  56. if btn.count() > 0 and btn.is_visible():
  57. btn.click(timeout=1500)
  58. page.wait_for_timeout(250)
  59. continue
  60. # 2) 常见的 close icon
  61. close_btn = page.locator(
  62. "css=.el-dialog__headerbtn, .el-message-box__headerbtn, .close, .icon-close, .el-icon-close"
  63. ).first
  64. if close_btn.count() > 0 and close_btn.is_visible():
  65. close_btn.click(timeout=1200)
  66. page.wait_for_timeout(250)
  67. continue
  68. break
  69. # 3) 清遮罩 + 恢复滚动/交互
  70. page.evaluate(r"""
  71. () => {
  72. // 第一步:精准清理已知的遮罩/弹窗类名(Element UI框架常用)
  73. const selectors = [
  74. '.v-modal', '.el-overlay', '.el-overlay-dialog', '.el-dialog__wrapper',
  75. '.el-message-box__wrapper', '.el-loading-mask'
  76. ];
  77. selectors.forEach(sel => document.querySelectorAll(sel).forEach(e => e.remove()));
  78. // 泛化兜底:近似全屏 + 高 z-index 的层直接屏蔽
  79. const all = Array.from(document.querySelectorAll('body *'));
  80. for (const el of all) {
  81. const s = getComputedStyle(el); // 获取元素的实际样式(含CSS生效的样式)
  82. const z = parseInt(s.zIndex || '0', 10); // 取元素的层级(z-index),默认0
  83. // 条件1:元素是固定/绝对定位(弹窗/遮罩常见定位方式)+ 层级≥1000(高优先级遮挡)+ 能拦截鼠标事件
  84. if ((s.position === 'fixed' || s.position === 'absolute') && z >= 1000 && s.pointerEvents !== 'none') {
  85. const r = el.getBoundingClientRect(); // 获取元素的尺寸和位置
  86. // 条件2:元素宽度/高度≥屏幕80%(近似全屏遮罩)
  87. const nearFull = r.width >= innerWidth * 0.8 && r.height >= innerHeight * 0.8;
  88. if (nearFull) {
  89. el.style.pointerEvents = 'none'; // 让元素不拦截鼠标点击
  90. el.style.display = 'none'; // 隐藏元素
  91. }
  92. }
  93. }
  94. // 第三步:恢复页面滚动功能(弹窗常把页面设为不可滚动)
  95. document.documentElement.style.overflow = 'auto'; // html标签恢复滚动
  96. document.body.style.overflow = 'auto'; // body标签恢复滚动
  97. document.body.classList.remove('el-popup-parent--hidden'); // 移除Element UI的滚动禁用类
  98. }
  99. """)
  100. # logger.info("杀除弹窗成功")
  101. except Exception:
  102. pass
  103. SEARCH_INPUT_SELECTOR = "input[placeholder*='药品名称/厂家名称']"
  104. def pick_search_input(page):
  105. """优先选可见且可用的搜索输入框;第一个不行就尝试第二个"""
  106. inputs = page.locator(SEARCH_INPUT_SELECTOR)
  107. cnt = inputs.count()
  108. # 优先检查前两个(你说只有两个)
  109. for i in range(min(cnt, 2)):
  110. candidate = inputs.nth(i)
  111. try:
  112. candidate.wait_for(state="visible", timeout=1500) # 小超时快速试探
  113. if candidate.is_enabled():
  114. return candidate
  115. except PlaywrightTimeoutError:
  116. continue
  117. # 兜底:直接找任意可见的(避免命中 hidden 模板)
  118. candidate = page.locator(f"{SEARCH_INPUT_SELECTOR}:visible").first
  119. candidate.wait_for(state="visible", timeout=5000)
  120. return candidate
  121. def type_slow(locator, text: str, min_delay=0.06, max_delay=0.18):
  122. """逐字输入,模拟真人打字"""
  123. for ch in text:
  124. locator.type(ch, delay=int(random.uniform(min_delay, max_delay) * 1000))
  125. SEARCH_BTN_SELECTOR = 'div.home-search-container-search-head-btn[data-scmd="text-搜索"]'
  126. def force_close_popup(page):
  127. """关闭新手引导/遮罩(多步:下一步/完成/我知道了),并兜底移除遮罩层"""
  128. try:
  129. # 1) 尝试连续点“下一步/完成/我知道了/关闭”
  130. for _ in range(5): # 最多点5次,足够覆盖多步引导
  131. btn = page.locator(
  132. "//button[normalize-space()='下一步' or normalize-space()='完成' or normalize-space()='我知道了' or normalize-space()='关闭']"
  133. ).first
  134. if btn.count() > 0 and btn.is_visible():
  135. btn.click(timeout=1500)
  136. page.wait_for_timeout(300)
  137. continue
  138. # 有些引导是右上角 X(如果存在就点)
  139. close_icon = page.locator(
  140. "xpath=//*[contains(@class,'close') or contains(@class,'el-icon-close') or name()='svg' or name()='i'][1]"
  141. ).first
  142. if close_icon.count() > 0 and close_icon.is_visible():
  143. close_icon.click(timeout=1000)
  144. page.wait_for_timeout(300)
  145. continue
  146. break
  147. # 2) 兜底:移除常见遮罩层(element-ui / 通用 mask/overlay)
  148. page.evaluate("""
  149. const selectors = [
  150. '.v-modal', '.el-overlay', '.el-overlay-dialog', '.el-dialog__wrapper',
  151. '[class*="mask"]', '[class*="overlay"]', '[style*="z-index"]'
  152. ];
  153. for (const sel of selectors) {
  154. document.querySelectorAll(sel).forEach(el => {
  155. const s = window.getComputedStyle(el);
  156. // 只移除“覆盖层”倾向的元素:fixed/absolute 且 z-index 很高
  157. if ((s.position === 'fixed' || s.position === 'absolute') && parseInt(s.zIndex || '0', 10) >= 1000) {
  158. el.remove();
  159. }
  160. });
  161. }
  162. """)
  163. except Exception:
  164. pass
  165. def kill_masks(page):
  166. """
  167. 强制清理残留遮罩层/覆盖层,并恢复 body 可滚动、可点击状态
  168. """
  169. page.evaluate(r"""
  170. () => {
  171. const removed = [];
  172. const hidden = [];
  173. // 1) 先处理已知常见遮罩
  174. const knownSelectors = [
  175. '.v-modal',
  176. '.el-overlay',
  177. '.el-overlay-dialog',
  178. '.el-dialog__wrapper',
  179. '.el-message-box__wrapper',
  180. '.el-loading-mask',
  181. '.el-popup-parent--hidden'
  182. ];
  183. for (const sel of knownSelectors) {
  184. document.querySelectorAll(sel).forEach(el => {
  185. // v-modal / overlay 直接 remove 最省事
  186. removed.push(sel);
  187. el.remove();
  188. });
  189. }
  190. // 2) 再做一次“泛化兜底”:全屏 fixed/absolute + 高 z-index 的覆盖层
  191. // 注意:不要误删页面正常的固定导航,所以加上“近似全屏”的判断
  192. const all = Array.from(document.querySelectorAll('body *'));
  193. for (const el of all) {
  194. const s = window.getComputedStyle(el);
  195. if (!s) continue;
  196. const z = parseInt(s.zIndex || '0', 10);
  197. const pos = s.position;
  198. const pe = s.pointerEvents;
  199. if ((pos === 'fixed' || pos === 'absolute') && z >= 1000 && pe !== 'none') {
  200. const r = el.getBoundingClientRect();
  201. const nearFullScreen =
  202. r.width >= window.innerWidth * 0.8 &&
  203. r.height >= window.innerHeight * 0.8 &&
  204. r.left <= window.innerWidth * 0.1 &&
  205. r.top <= window.innerHeight * 0.1;
  206. // 常见遮罩是半透明背景色,或者透明但拦截点击
  207. const bg = s.backgroundColor || '';
  208. const looksLikeMask =
  209. nearFullScreen && (bg.includes('rgba') || bg.includes('rgb') || s.opacity !== '1');
  210. if (nearFullScreen) {
  211. // 不管透明不透明,只要近似全屏且高 z-index,就先让它不拦截点击
  212. el.style.pointerEvents = 'none';
  213. el.style.display = 'none';
  214. hidden.push(el.tagName + '.' + (el.className || ''));
  215. }
  216. }
  217. }
  218. // 3) 恢复 body / html 的滚动与交互(很多弹窗会锁滚动)
  219. document.documentElement.style.overflow = 'auto';
  220. document.body.style.overflow = 'auto';
  221. document.body.style.position = 'static';
  222. document.body.style.width = 'auto';
  223. document.body.style.paddingRight = '0px';
  224. // 4) 去掉 Element-UI 常见的锁定 class
  225. document.body.classList.remove('el-popup-parent--hidden');
  226. return { removed, hiddenCount: hidden.length, hidden };
  227. }
  228. """)
  229. # ==================== 搜索操作函数 ====================
  230. def search_operation(page, keyword, is_first_search: bool = True):
  231. """
  232. 搜索框填充+提交搜索
  233. :param page: 页面对象
  234. :param keyword: 搜索关键词
  235. :param is_first_search: 是否是首次搜索(首次开新页面,后续原页面跳转)
  236. :return: (detail_page, 是否成功)
  237. """
  238. try:
  239. # 1) 找到“可用”的搜索框(第一个不行就用第二个)
  240. search_locator = page.locator(SEARCH_INPUT_SELECTOR)
  241. # 清空并填充搜索框
  242. search_locator.wait_for(timeout=ELEMENT_TIMEOUT)
  243. # 2. 清空搜索框(双重保障:先调用locator的clear,再手动全选删除)
  244. search_locator.click(force=True) # 聚焦
  245. search_locator.fill("")
  246. page.keyboard.down("Control") # 按住Control键
  247. page.keyboard.press("a") # 按a键
  248. page.keyboard.up("Control") # 松开Control键
  249. page.keyboard.press("Backspace") # 删除选中内容
  250. # 3) 逐字输入
  251. type_slow(search_locator, keyword, min_delay=0.06, max_delay=0.18)
  252. # 3. 输入搜索关键词
  253. # search_locator.fill(keyword)
  254. logger.info(f"📝 已输入搜索关键词:{keyword}")
  255. # 3) 搜索按钮也建议点可见的那个
  256. btn = page.locator(f"{SEARCH_BTN_SELECTOR}")
  257. btn.wait_for(state="visible", timeout=SEARCH_BTN_TIMEOUT)
  258. # btn.click()
  259. page.wait_for_timeout(3000)
  260. detail_page = page
  261. if is_first_search:
  262. #获取新页面对象
  263. try:
  264. # 先开始监听新页面事件(在点击前)
  265. with page.context.expect_page(timeout=60000) as new_page_info:
  266. # 再执行点击操作
  267. btn.click()
  268. # 点击后获取新页面
  269. detail_page = new_page_info.value
  270. detail_page.wait_for_load_state("networkidle", timeout=20000)
  271. # #点击出现的按钮
  272. # test_btn = detail_page.locator("div[data-v-c65c36bc].first-time-highlight-message-btn button")
  273. # btn_count = test_btn.count()
  274. # logger.info(f"✅ 匹配到的元素数量:{btn_count}")
  275. # test_btn.wait_for(state="attached", timeout=5000)
  276. # test_btn.click()
  277. except PlaywrightTimeoutError:
  278. logger.warning(f" 未检测到新标签页")
  279. return None, False
  280. except Exception as e:
  281. logger.warning(f" 等待新标签页异常:{e}")
  282. return None, False
  283. else:
  284. btn.click()
  285. # 等待原页面跳转并加载完成(替代新页面监听)
  286. page.wait_for_load_state("networkidle", timeout=20000)
  287. # 详情页就是原页面,无需新建
  288. detail_page = page
  289. logger.info("✅ 后续搜索:已在原页面完成跳转加载")
  290. test_btn = detail_page.locator("div[data-v-c65c36bc].first-time-highlight-message-btn button")
  291. btn_count = test_btn.count()
  292. logger.info(f"✅ 匹配到的元素数量:{btn_count}")
  293. if btn_count > 0:
  294. test_btn.wait_for(state="attached", timeout=5000)
  295. test_btn.click()
  296. force_close_popup(detail_page)
  297. kill_masks(detail_page)
  298. logger.info("✅ 已触发搜索")
  299. return detail_page, True
  300. # 搜索后等待结果加载
  301. # page.wait_for_timeout(COLLECT_DELAY)
  302. # return True
  303. except PlaywrightTimeoutError as e:
  304. logger.error(f" 搜索失败:元素定位超时 - {str(e)}")
  305. return None, False # 失败时返回 (None, False)
  306. except Exception as e:
  307. logger.error(f" 搜索异常:{str(e)}")
  308. return None, False # 失败时返回 (None, False)
  309. def main():
  310. with sync_playwright() as p:
  311. browser = p.chromium.launch(
  312. headless=False, # 不要用无头模式(反爬:无头模式易被识别)
  313. channel="chrome", # 使用真实Chrome内核
  314. slow_mo=random.randint(100, 300), # 全局操作延迟(模拟真人慢速操作)
  315. args=[
  316. "--disable-blink-features=AutomationControlled", # 禁用webdriver特征(核心!)
  317. "--enable-automation=false", # 新增:禁用自动化标识
  318. "--disable-infobars", # 新增:禁用信息栏
  319. "--remote-debugging-port=0", # 新增:随机调试端口
  320. "--start-maximized", # 最大化窗口(模拟真人使用)
  321. "--disable-extensions", # 禁用扩展(避免特征)
  322. "--disable-plugins-discovery", # 禁用插件发现
  323. "--no-sandbox", # 避免沙箱模式特征
  324. "--disable-dev-shm-usage", # 避免内存限制导致的异常
  325. f"--user-agent=Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/{random.randint(110, 120)}.0.0.0 Safari/537.36" # 随机Chrome版本的UA
  326. ]
  327. )
  328. # 创建页面时伪装指纹
  329. context = browser.new_context(
  330. locale="zh-CN", # 中文环境
  331. timezone_id="Asia/Shanghai", # 上海时区
  332. geolocation={"latitude": 31.230416, "longitude": 121.473701}, # 模拟上海地理位置(可选)
  333. permissions=["geolocation"], # 授予定位权限(模拟真人)
  334. user_agent="Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36",
  335. no_viewport=True,
  336. # 关键:隐藏自动化特征
  337. java_script_enabled=True,
  338. bypass_csp=True,
  339. # user_data_dir="./temp_user_data" # 模拟真实用户数据目录
  340. )
  341. input("...")
  342. page = context.new_page()
  343. # 关键:移除navigator.webdriver标识(反爬核心)
  344. page.add_init_script("""
  345. Object.defineProperty(navigator, 'webdriver', { get: () => undefined });
  346. Object.defineProperty(navigator, 'plugins', { get: () => [1, 2, 3] }); // 新增:模拟插件
  347. Object.defineProperty(navigator, 'mimeTypes', { get: () => [1, 2, 3] }); // 新增:模拟MIME类型
  348. window.chrome = { runtime: {}, loadTimes: () => ({}) }; // 增强Chrome模拟
  349. delete window.navigator.languages;
  350. window.navigator.languages = ['zh-CN', 'zh'];
  351. // 新增:模拟真实鼠标移动特征
  352. (() => {
  353. const originalAddEventListener = EventTarget.prototype.addEventListener;
  354. EventTarget.prototype.addEventListener = function(type, listener) {
  355. if (type === 'mousemove') {
  356. return originalAddEventListener.call(this, type, (e) => {
  357. e._automation = undefined;
  358. listener(e);
  359. });
  360. }
  361. return originalAddEventListener.call(this, type, listener);
  362. };
  363. })();
  364. """)
  365. try:
  366. # ========== 核心:Cookie复用逻辑 ==========
  367. # 1. 加载本地Cookie
  368. load_cookies(context)
  369. # 2. 验证登录状态
  370. if not is_login(page):
  371. # 3. Cookie失效/不存在,执行登录
  372. page.goto(TARGET_LOGIN_URL)
  373. page.wait_for_load_state("networkidle")
  374. # logger.info("🔑 开始执行登录流程")
  375. # 执行登录操作
  376. # login_success = login_operation(page, USERNAME, PASSWORD)
  377. # if not login_success:
  378. # logger.error(" 登录失败,程序终止")
  379. # return
  380. # # 4. 登录成功后保存Cookie
  381. # save_cookies(context)
  382. # logger.info(" 登录并保存Cookie成功!")
  383. KEYWORDS = get_search_keywords_from_db()
  384. # get_search_keywords_from_db()
  385. # 执行搜索
  386. total_num = 0
  387. # current_page = page
  388. detail_page = None
  389. nums = 0
  390. for kw in KEYWORDS:
  391. popup_guard(page, "before_search")
  392. if nums == 0:
  393. popup_guard(detail_page if detail_page else page, "before_search") # page是你的初始页面对象,需提前定义
  394. detail_page, search_success = search_operation(page, kw, is_first_search=True)
  395. nums += 1
  396. else:
  397. if detail_page is None:
  398. logger.error(f" ❌ 无可用的搜索页面,跳过「{kw}」")
  399. continue
  400. popup_guard(detail_page, "before_search")
  401. detail_page, search_success = search_operation(detail_page, kw, is_first_search=False)
  402. if not search_success:
  403. print(f"❌ 搜索失败:{kw}")
  404. continue
  405. if detail_page is None:
  406. break
  407. popup_guard(detail_page, "after_search")
  408. #找不到数据跳过判断和出现杂数据跳过
  409. not_found_keywords = detail_page.locator("div.filter-panel-container-empty-text")
  410. if not_found_keywords.count() > 0:
  411. logger.warning(f"⚠️ 关键词「{kw}」无匹配商品,直接跳过整个关键词采集")
  412. continue
  413. TARGET_SELECTOR = detail_page.locator(
  414. 'span.el-pagination__total', # 匹配class为el-pagination_total和is-first的span
  415. )
  416. total_count = 0 # ⚠️ 每一轮关键词都重置
  417. if TARGET_SELECTOR.count() > 0:
  418. nums = TARGET_SELECTOR.inner_text(timeout=5000).strip()
  419. print(nums)
  420. match = re.search(r'\d+', nums)
  421. if match:
  422. total_count = int(match.group())
  423. print(total_count)
  424. else:
  425. itme_boxes = detail_page.locator("div.product-list-item")
  426. total_count = itme_boxes.count()
  427. #
  428. print(f"【{kw}】无分页,当前页盒子数:{total_count}")
  429. total_num += total_count
  430. print(f"截止到这个{kw}关键词有{total_num}条数据")
  431. page.wait_for_timeout(10000)
  432. print(f"✅ 本次采集总数据量:{total_num}")
  433. except Exception as e:
  434. print(f" 程序异常:{str(e)}")
  435. finally:
  436. browser.close()
  437. print(" 浏览器已关闭,程序结束")
  438. # ==================== 程序入口 ====================
  439. if __name__ == '__main__':
  440. main()