jd_auto_crawl.py 24 KB

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