jd_auto_crawl_snap.py 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711
  1. import random
  2. import re
  3. import signal
  4. import socket
  5. import sys
  6. import time
  7. from decimal import Decimal, InvalidOperation
  8. from urllib.parse import quote
  9. from DrissionPage import ChromiumPage, ChromiumOptions
  10. import json
  11. import hashlib
  12. from commons.Logger import get_spider_logger
  13. from commons.conn_mysql import MySQLPoolOnline
  14. from pipelines.drug_pipelines import DrugPipeline
  15. from commons.feishu_webhook import send_text
  16. from spiders.jd.jd_captcha import handle_jd_slider_captcha
  17. from oss_upload.oss_upload import AliyunOSSUploader
  18. logger = get_spider_logger("jd")
  19. chrome_path = r"C:\Program Files\Google\Chrome\Application\chrome.exe"
  20. FETCH_TIMEOUT_FIRST = 5
  21. FETCH_TIMEOUT_SCROLL = 6
  22. LISTEN_CLEAR_ROUNDS = 3
  23. LISTEN_CLEAR_TIMEOUT = 0.45
  24. # 「下一页」是否在视口内(条件略宽)
  25. _JS_NEXT_BTN_IN_VIEWPORT = """
  26. var el = arguments[0];
  27. if (!el) return false;
  28. var r = el.getBoundingClientRect();
  29. var h = window.innerHeight || document.documentElement.clientHeight || 800;
  30. var w = window.innerWidth || document.documentElement.clientWidth || 1200;
  31. return r.bottom > 80 && r.top < h - 40 && r.right > 0 && r.left < w;
  32. """
  33. class JdCrawlerV2:
  34. def __init__(self, drug_dict=None, scheduler=None):
  35. self.driver = None
  36. self.register_signal_handler()
  37. self.db = MySQLPoolOnline()
  38. self.ip = None
  39. self.account_name = None
  40. self.login_username = None
  41. self.login_password = None
  42. self.platform = 2
  43. self.pipeline = DrugPipeline("jd")
  44. self.task_dict = drug_dict or {}
  45. self.scheduler = scheduler
  46. self.ossuploader = AliyunOSSUploader()
  47. self.start_page = 1
  48. self.end_page = 1
  49. if self.task_dict:
  50. self.get_product_data()
  51. self.success = True
  52. self.is_no_prodcut = 0
  53. def get_product_data(self):
  54. self.task_id = self.task_dict["id"]
  55. self.company_id = self.task_dict["company_id"]
  56. self.product = self.task_dict["product_name"]
  57. self.product_desc = self.task_dict.get("product_specs", "")
  58. self.brand = self.task_dict.get("product_brand", "")
  59. self.product_keyword = self.task_dict.get("product_keyword", "")
  60. self.collect_task_id = self.task_dict.get("collect_task_id", "")
  61. self.sampling_cycle = self.task_dict.get("sampling_cycle", "")
  62. self.sampling_start_time = self.task_dict.get("sampling_start_time", "")
  63. self.sampling_end_time = self.task_dict.get("sampling_end_time", "")
  64. self.collect_equipment_id = self.task_dict.get("collect_equipment_id", "")
  65. self.account_id = self.task_dict.get("collect_equipment_account_id", "15")
  66. self.collect_region_id = self.task_dict.get("collect_region_id", "")
  67. self.collect_round = self.task_dict.get("collect_round", 1)
  68. self.start_page = self._parse_page(self.task_dict.get("start_page"), 1)
  69. self.end_page = self._parse_page(self.task_dict.get("end_page"), 15)
  70. @staticmethod
  71. def _parse_page(value, default=1):
  72. try:
  73. page = int(value)
  74. return page if page >= 1 else default
  75. except (TypeError, ValueError):
  76. return default
  77. @staticmethod
  78. def _get_free_port():
  79. """获取一个当前可用的本地端口,供 Chrome 调试使用。"""
  80. with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
  81. s.bind(("127.0.0.1", 0))
  82. return s.getsockname()[1]
  83. def init_browser(self):
  84. co = ChromiumOptions().set_browser_path(chrome_path)
  85. debug_port = self._get_free_port()
  86. co.set_user_data_path(f"./spiders/jd/JD_101")
  87. co.set_local_port(debug_port)
  88. co.set_argument(f"--remote-debugging-port={debug_port}")
  89. co.set_argument("--remote-debugging-address=127.0.0.1")
  90. # co.set_argument("--disable-blink-features=AutomationControlled")
  91. co.set_argument("--disable-dev-shm-usage")
  92. co.set_argument("--no-first-run") # 避免首次运行弹窗
  93. co.set_argument("--no-default-browser-check") # 避免默认浏览器检查
  94. if self.ip:
  95. proxy = self.ip.strip()
  96. if not proxy.startswith(("http://", "https://")):
  97. proxy = f"http://{proxy}"
  98. co.set_argument(f"--proxy-server={proxy}")
  99. logger.info("启动浏览器: account=%s, debug_port=%s", self.account_name, debug_port)
  100. self.driver = ChromiumPage(co)
  101. self._listen_started = False
  102. def _start_listen(self):
  103. """登录完成后再开监听,避免干扰登录页/验证码拖动。"""
  104. if self._listen_started or not self.driver:
  105. return
  106. self.driver.listen.start("api?appid=search-pc-java")
  107. self._listen_started = True
  108. logger.info("已启动搜索接口监听")
  109. def register_signal_handler(self):
  110. def handler(signum, frame):
  111. print("\n⚠️ 程序退出")
  112. if self.driver:
  113. self.driver.quit()
  114. sys.exit(0)
  115. signal.signal(signal.SIGINT, handler)
  116. if hasattr(signal, "SIGTERM"):
  117. signal.signal(signal.SIGTERM, handler)
  118. def sleep(self, a, b):
  119. time.sleep(random.uniform(a, b))
  120. def _scroll_page_down(self, delta=900):
  121. self.driver.run_js(f"window.scrollBy(0, {int(delta)});")
  122. time.sleep(random.uniform(0.3, 0.6))
  123. def _scroll_next_into_view(self, el):
  124. if not el:
  125. return
  126. try:
  127. self.driver.run_js(
  128. "arguments[0].scrollIntoView({block:'center',behavior:'instant'});",
  129. el,
  130. )
  131. self.sleep(1, 2)
  132. except Exception as e:
  133. logger.warning("滚动到下一页按钮失败: %s", e)
  134. try:
  135. el.scroll.to_see()
  136. except Exception:
  137. pass
  138. def _get_scroll_info(self):
  139. return self.driver.run_js("""
  140. return {
  141. scrollY: window.scrollY || window.pageYOffset || 0,
  142. docH: Math.max(document.body.scrollHeight,
  143. document.documentElement.scrollHeight,
  144. document.body.offsetHeight),
  145. viewH: window.innerHeight || document.documentElement.clientHeight || 800
  146. };
  147. """)
  148. def _find_next_btn(self, timeout=0.3):
  149. try:
  150. return self.driver.ele("text=下一页", timeout=timeout)
  151. except Exception:
  152. return None
  153. def _is_next_btn_visible(self, btn):
  154. if not btn:
  155. return False
  156. try:
  157. return bool(self.driver.run_js(_JS_NEXT_BTN_IN_VIEWPORT, btn))
  158. except Exception:
  159. return False
  160. def _human_click(self, element):
  161. """在目标节点上触发 click,避免 move_to + 无目标 actions.click() 因布局位移点到商品链接触发详情页。"""
  162. if not element:
  163. return False
  164. try:
  165. self.sleep(0.8, 2.0)
  166. try:
  167. self.driver.run_js(
  168. "arguments[0].scrollIntoView({block:'center',behavior:'instant'});",
  169. element,
  170. )
  171. except Exception:
  172. pass
  173. self.sleep(0.2, 0.6)
  174. self.driver.run_js("arguments[0].click();", element)
  175. return True
  176. except Exception as e:
  177. logger.warning("点击失败: %s", e)
  178. try:
  179. element.click()
  180. return True
  181. except Exception:
  182. return False
  183. @staticmethod
  184. def _estimated_price(json_data):
  185. fp = json_data.get("finalPrice")
  186. if isinstance(fp, dict):
  187. return fp.get("estimatedPrice", "") or ""
  188. return ""
  189. def get_heshu(self,full_title):
  190. last_box = None
  191. last_bottle = None
  192. for match in re.finditer(r"(\d+)(盒|瓶)", full_title):
  193. if match.group(2) == '盒':
  194. last_box = match
  195. else: # 瓶
  196. last_bottle = match
  197. if last_box:
  198. return int(last_box.group(1))
  199. elif last_bottle:
  200. return int(last_bottle.group(1))
  201. else:
  202. return 1
  203. def _take_snapshot(self, upload_key, ele):
  204. """在指定标签页截图并上传。"""
  205. time.sleep(1)
  206. try:
  207. jpg_bytes = ele.get_screenshot(as_bytes="jpg")
  208. if not jpg_bytes:
  209. logger.warning("截图为空 upload_key=%s", upload_key)
  210. return ""
  211. img_url = self.ossuploader.upload_from_bytes(jpg_bytes, str(upload_key))
  212. except Exception:
  213. logger.exception("截图或 OSS 上传失败 upload_key=%s", upload_key)
  214. return ""
  215. if not img_url:
  216. logger.warning("OSS 未返回有效地址 upload_key=%s", upload_key)
  217. return ""
  218. logger.info("截图上传完成 upload_key=%s url=%s", upload_key, img_url)
  219. time.sleep(random.uniform(1, 2))
  220. return img_url
  221. def get_heshu(self,full_title):
  222. last_box = None
  223. last_bottle = None
  224. for match in re.finditer(r"(\d+)(盒|瓶)", full_title):
  225. if match.group(2) == '盒':
  226. last_box = match
  227. else: # 瓶
  228. last_bottle = match
  229. if last_box:
  230. return int(last_box.group(1))
  231. elif last_bottle:
  232. return int(last_bottle.group(1))
  233. else:
  234. return 1
  235. def parse(self, ware_list):
  236. for w in ware_list:
  237. title = w.get("wareName", "")
  238. title = re.sub(r"<[^>]*>", "", title).strip()
  239. color = w.get("color", "")
  240. full_title = title + " " + color
  241. logger.info(full_title)
  242. if self.product not in full_title:
  243. self.is_no_prodcut += 1
  244. continue
  245. if self.brand not in full_title:
  246. self.is_no_prodcut += 1
  247. continue
  248. if self.product_desc:
  249. if self.product_desc in full_title:
  250. crawl_product_desc = self.product_desc
  251. else:
  252. crawl_product_desc = ""
  253. title = full_title
  254. else:
  255. crawl_product_desc = ""
  256. title = full_title
  257. if "+[" in title:
  258. continue
  259. self.is_no_prodcut = 0
  260. status = 1
  261. if self.product_keyword:
  262. search_keyword_list = self.product_keyword.split(",")
  263. for search_keyword in search_keyword_list:
  264. if search_keyword.strip() not in title:
  265. status = 0
  266. if status == 0:
  267. continue
  268. logger.info(f"商品名:{title}")
  269. sku_id = w.get("skuId", "")
  270. sales = w.get("totalSales", "")
  271. shop_id = w.get("shopId", "")
  272. shop_name = w.get("shopName", "")
  273. heshu_count = self.get_heshu(full_title)
  274. final_price = self._estimated_price(w)
  275. jd_price = w.get("jdPrice", "")
  276. item_url = f"https://item.jd.com/{sku_id}.html"
  277. low_price = final_price if final_price else jd_price
  278. # 获取列表页快照
  279. ele_xpath = "//div[@id='main_search_conter']//div[contains(@class,'_goodsContainer_')]/div[@data-sku=" + "'" + sku_id + "'" + "]"
  280. ele_screen = self.driver.ele("xpath="+ele_xpath)
  281. upload_key = hashlib.md5(item_url.encode("utf-8")).hexdigest()
  282. for i in range(3):
  283. snap_url = self._take_snapshot(upload_key,ele_screen)
  284. if snap_url != "":
  285. break
  286. try:
  287. price = Decimal(str(low_price)).quantize(Decimal("0.00"))
  288. except (InvalidOperation, ValueError):
  289. price = Decimal("0.00")
  290. item_url = f"https://item.jd.com/{sku_id}.html"
  291. mall_url = f"https://mall.jd.com/index-{shop_id}.html?from=pc"
  292. # 字段与 yaofangwang_crawl 对齐;键顺序须与 commons.sql_data.RETRIEVE_SCRAPE_INSERT_COLUMNS 一致
  293. now_ts = time.strftime("%Y-%m-%d %H:%M:%S")
  294. product = {
  295. "platform": self.platform,
  296. "item_id": sku_id,
  297. "enterprise_id": self.company_id,
  298. "product_name": title,
  299. "spec": crawl_product_desc,
  300. "one_price": "",
  301. "detail_url": item_url,
  302. "shop_name": shop_name,
  303. "anonymous_store_name": "",
  304. "shop_url": mall_url,
  305. "city_name": "",
  306. "city_id": "",
  307. "province_name": "",
  308. "province_id": "",
  309. "shipment_city_name": "",
  310. "shipment_city_id": "",
  311. "shipment_province_name": "",
  312. "shipment_province_id": "",
  313. "area_info": "",
  314. "factory_name": "",
  315. "scrape_date": time.strftime("%Y-%m-%d"),
  316. "price": price,
  317. "sales": sales,
  318. "stock_count": "",
  319. "snapshot_url": snap_url,
  320. "approval_num": "",
  321. "produced_time": "",
  322. "deadline": "",
  323. "update_time": now_ts,
  324. "insert_time": now_ts,
  325. "number": heshu_count,
  326. "product_brand": self.brand or "",
  327. "collect_task_id": self.collect_task_id,
  328. "task_id": self.task_id,
  329. "search_name": self.product,
  330. "company_name": "",
  331. "collect_config_info": json.dumps(
  332. {
  333. "sampling_cycle": self.sampling_cycle,
  334. "sampling_start_time": self.sampling_start_time,
  335. "sampling_end_time": self.sampling_end_time,
  336. }
  337. ),
  338. "account_id": self.account_id,
  339. "collect_region_id": self.collect_region_id,
  340. "collect_round": self.collect_round,
  341. "is_sold_out": 0
  342. }
  343. try:
  344. self.pipeline.storge_data(product)
  345. logger.info("%s", json.dumps(product, ensure_ascii=False, default=str))
  346. except Exception as e:
  347. logger.exception("写入数据库失败: %s", e)
  348. @staticmethod
  349. def _response_has_ware_list(data):
  350. if not isinstance(data, dict):
  351. return False
  352. wl = data.get("data", {}).get("wareList")
  353. return bool(wl)
  354. def fetch_items_once(self, timeout=FETCH_TIMEOUT_FIRST):
  355. n = 0
  356. for resp in self.driver.listen.steps(timeout=timeout):
  357. try:
  358. data = resp.response.body
  359. if not self._response_has_ware_list(data):
  360. continue
  361. ware_list = data["data"]["wareList"]
  362. self.parse(ware_list)
  363. n += len(ware_list)
  364. except Exception as e:
  365. logger.warning("解析监听响应失败: %s", e)
  366. return n
  367. def clear_listen_buffer(self, rounds=LISTEN_CLEAR_ROUNDS, timeout=LISTEN_CLEAR_TIMEOUT):
  368. try:
  369. for _ in range(rounds):
  370. resps = list(self.driver.listen.steps(timeout=timeout))
  371. if not resps:
  372. break
  373. logger.debug("监听缓冲已清空")
  374. except Exception as e:
  375. logger.debug("清空监听缓冲失败: %s", e)
  376. def collect_full_page_items(self, max_steps=10):
  377. """单次循环:边滑动边收数据,到底 / 看见「下一页」即停。"""
  378. n = self.fetch_items_once(timeout=FETCH_TIMEOUT_FIRST)
  379. stagnant = 0
  380. last_scroll_y = None
  381. for step in range(max_steps):
  382. next_btn = self._find_next_btn(timeout=0.3)
  383. if self._is_next_btn_visible(next_btn):
  384. n += self.fetch_items_once(timeout=FETCH_TIMEOUT_SCROLL)
  385. return n, next_btn
  386. info = self._get_scroll_info()
  387. scroll_y = info["scrollY"]
  388. doc_h = info["docH"]
  389. view_h = info["viewH"]
  390. at_bottom = (scroll_y + view_h >= doc_h - 20)
  391. if last_scroll_y is not None and abs(scroll_y - last_scroll_y) < 8:
  392. stagnant += 1
  393. else:
  394. stagnant = 0
  395. last_scroll_y = scroll_y
  396. if at_bottom and stagnant >= 2:
  397. n += self.fetch_items_once(timeout=FETCH_TIMEOUT_SCROLL)
  398. next_btn = self._find_next_btn(timeout=2)
  399. if next_btn:
  400. self._scroll_next_into_view(next_btn)
  401. return n, next_btn
  402. logger.info("已到页面底部且未发现下一页,停止滑动")
  403. return n, None
  404. self._scroll_page_down(random.randint(400, 800))
  405. if random.random() < 0.15:
  406. self.driver.run_js(f"window.scrollBy(0, -{random.randint(60, 140)})")
  407. self.sleep(0.5, 1.5)
  408. if step % 3 == 2:
  409. n += self.fetch_items_once(timeout=FETCH_TIMEOUT_SCROLL)
  410. n += self.fetch_items_once(timeout=FETCH_TIMEOUT_SCROLL)
  411. next_btn = self._find_next_btn(timeout=3)
  412. if next_btn and not self._is_next_btn_visible(next_btn):
  413. self._scroll_next_into_view(next_btn)
  414. return n, next_btn
  415. def get_account(self):
  416. sql_account = """
  417. SELECT *
  418. FROM `retrieve_collect_equipment_account`
  419. WHERE `id` = %s
  420. and `status` = 0
  421. """
  422. account_list = self.db.select_data(sql_account, self.account_id)
  423. if not account_list:
  424. return False
  425. account_dict = account_list[0]
  426. print(account_dict)
  427. self.ip = account_dict.get("ip")
  428. self.account_name = account_dict.get("username")
  429. self.login_username = account_dict.get("phone", "")
  430. self.login_password = account_dict.get("password", "")
  431. logger.info("获取到账号: %s, ip: %s", self.account_name, self.ip)
  432. return True
  433. def disable_account(self):
  434. update_sql = f""" UPDATE `retrieve_collect_equipment_account` SET `status`= %s WHERE `name` = %s; """
  435. self.db.execute(update_sql, (1, self.account_name))
  436. def _build_search_keyword(self):
  437. parts = [p for p in (self.brand, self.product, self.product_desc) if p]
  438. return " ".join(parts).strip() or self.product
  439. def _is_logged_out(self):
  440. return bool(self.driver.ele("xpath=//*[@class='link-login']", timeout=2))
  441. def perform_jd_login(self):
  442. """
  443. 使用已有浏览器实例执行京东账号密码登录(含滑块验证码)。
  444. 成功返回 True,失败返回 False。
  445. """
  446. username = self.login_username
  447. password = self.login_password
  448. login_url = "https://passport.jd.com/new/login.aspx"
  449. self.driver.get(login_url)
  450. input_name = self.driver.ele("xpath=//input[@id='loginname']", timeout=15)
  451. if not input_name:
  452. print("未找到用户名输入框")
  453. return False
  454. input_name.input(username)
  455. time.sleep(random.uniform(1.5, 2.5))
  456. input_pass = self.driver.ele("xpath://input[@name='nloginpwd']", timeout=5)
  457. if not input_pass:
  458. print("未找到密码输入框")
  459. return False
  460. input_pass.input(password)
  461. time.sleep(random.uniform(1.5, 2.5))
  462. login_btn = self.driver.ele("xpath://a[@id='loginsubmit']", timeout=5)
  463. if not login_btn:
  464. print("未找到登录按钮")
  465. return False
  466. login_btn.click()
  467. time.sleep(random.uniform(3, 5))
  468. if not handle_jd_slider_captcha(self.driver):
  469. print("滑块验证码未通过")
  470. return False
  471. return True
  472. def _ensure_logged_in(self):
  473. """未登录时自动走登录流程(账号密码 + 滑块)。"""
  474. if not self._is_logged_out():
  475. return True
  476. logger.info("检测到未登录,开始自动登录: %s", self.account_name)
  477. ok = self.perform_jd_login()
  478. if ok and not self._is_logged_out():
  479. logger.info("自动登录成功: %s", self.account_name)
  480. return True
  481. logger.error("自动登录失败: %s", self.account_name)
  482. return False
  483. def _check_page_blocked(self):
  484. html = self.driver.html or ""
  485. if "抱歉由于访问频繁导致无法搜索" in html:
  486. logger.error("账号无法搜索(访问频繁)")
  487. self.success = False
  488. return True
  489. return False
  490. def _jump_to_page(self, target_page):
  491. """跳转到指定页码,并清空跳转前的监听残留。"""
  492. to_page_input = self.driver.ele(
  493. "xpath=//div[contains(@class,'_pagination_toPageNum_')]//input[@type='text']",
  494. timeout=3,
  495. )
  496. if not to_page_input:
  497. logger.warning("未找到跳页输入框,无法跳转到第 %s 页", target_page)
  498. return False
  499. self.clear_listen_buffer()
  500. to_page_input.input(str(target_page))
  501. self.sleep(1, 2)
  502. self.driver.actions.key_down("enter").key_up("enter")
  503. self.sleep(3, 5)
  504. self.clear_listen_buffer()
  505. logger.info("已跳转到第 %s 页", target_page)
  506. return True
  507. def _go_next_page(self, next_btn):
  508. self.clear_listen_buffer()
  509. if not self._human_click(next_btn):
  510. logger.warning("点击下一页失败")
  511. return False
  512. self.sleep(2, 4)
  513. return True
  514. def crawl(self):
  515. total = 0
  516. keyword = self._build_search_keyword()
  517. self.driver.get("https://www.jd.com/", timeout=15)
  518. time.sleep(15)
  519. if self._is_logged_out():
  520. if not self.login_password or not self.login_username:
  521. return
  522. if not self._ensure_logged_in():
  523. self.disable_account()
  524. send_text(f"京东:{self.account_name}账号登录失败")
  525. self.success = False
  526. return
  527. self.driver.get("https://www.jd.com/", timeout=15)
  528. self.sleep(3, 5)
  529. kw = quote(str(keyword or ""), safe="")
  530. self._search_kw = kw
  531. # 必须先监听再打开搜索页,否则首屏 wareList(前约 30 条)在监听开启前就返回了
  532. self._start_listen()
  533. self.driver.get(
  534. f"https://search.jd.com/Search?keyword={kw}&enc=utf-8&wq={kw}", timeout=15
  535. )
  536. self.sleep(5, 8)
  537. if self._check_page_blocked():
  538. return
  539. if not handle_jd_slider_captcha(self.driver, pause_listen=False):
  540. logger.warning("进入搜索页后滑块验证码处理失败")
  541. self.success = False
  542. return
  543. if self.start_page > 1:
  544. if not self._jump_to_page(self.start_page):
  545. logger.warning("跳页失败,将从第 1 页开始采集")
  546. self.start_page = 1
  547. logger.info(
  548. "采集页码范围: %s ~ %s(共 %s 页)",
  549. self.start_page,
  550. self.end_page,
  551. self.end_page - self.start_page + 1,
  552. )
  553. for page_no in range(self.start_page, self.end_page + 1):
  554. if self._is_logged_out():
  555. if not self._ensure_logged_in():
  556. self.success = False
  557. break
  558. self.driver.get(
  559. f"https://search.jd.com/Search?keyword={kw}&enc=utf-8&wq={kw}",
  560. timeout=15,
  561. )
  562. self.sleep(3, 5)
  563. if page_no > 1:
  564. self._jump_to_page(page_no)
  565. if not handle_jd_slider_captcha(self.driver, pause_listen=True):
  566. logger.warning("滑块验证码处理失败,停止采集")
  567. self.success = False
  568. break
  569. if self._check_page_blocked():
  570. break
  571. logger.info("===== 正在爬取第 %s 页 =====", page_no)
  572. search_ele = self.driver.ele("xpath=//div[@id='search-condition']", timeout=10)
  573. if not search_ele:
  574. logger.warning("未找到搜索结果区域,停止采集")
  575. break
  576. page_n, _ = self.collect_full_page_items()
  577. logger.info("本页监听商品条数(含可能重复): %s", page_n)
  578. total += page_n
  579. logger.info("累计监听条数: %s", total)
  580. if self.is_no_prodcut > 20:
  581. logger.info("连续无匹配商品过多,停止采集")
  582. break
  583. if page_no >= self.end_page:
  584. break
  585. next_btn = self.driver.ele("text=下一页", timeout=2)
  586. if not next_btn:
  587. logger.info("没有下一页(未找到)")
  588. break
  589. cls_str = next_btn.attr("class") or ""
  590. if "disabled" in cls_str:
  591. logger.info("没有下一页(已禁用)")
  592. break
  593. if not self._go_next_page(next_btn):
  594. break
  595. def run(self):
  596. # 检测账号
  597. if not self.get_account():
  598. logger.info("==================当前无账号可用==================")
  599. self.success = False
  600. return self.pipeline.crawl_count, self.success
  601. logger.info("获取到账号:%s,代理ip:%s", self.account_name, self.ip)
  602. # # # 每次选取账号,立马账号使用时间
  603. update_sql = f""" UPDATE `retrieve_collect_equipment_account` SET `status`= %s, `update_time`= %s WHERE `username` = %s; """
  604. self.db.execute(update_sql, (0, int(time.time()), self.account_name))
  605. try:
  606. self.init_browser()
  607. self.crawl()
  608. except Exception as e:
  609. self.success = False
  610. logger.exception("爬取异常: %s", e)
  611. self.sleep(3, 5)
  612. finally:
  613. if self.driver:
  614. self.driver.quit()
  615. self.driver = None
  616. return self.pipeline.crawl_count, self.success