jd_auto_crawl.py 26 KB

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