jd_auto_crawl_snap2.py 32 KB

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