bobocup commited on
Commit
d70f2a2
·
verified ·
1 Parent(s): 451a2b3

Update nb2.py

Browse files
Files changed (1) hide show
  1. nb2.py +79 -36
nb2.py CHANGED
@@ -6,6 +6,10 @@ from selenium.webdriver.support.ui import WebDriverWait
6
  from selenium.webdriver.support import expected_conditions as EC
7
  from selenium.common.exceptions import TimeoutException
8
  from selenium.webdriver.common.keys import Keys
 
 
 
 
9
  import time
10
  import random
11
  import string
@@ -14,8 +18,6 @@ import requests
14
  import json
15
  import re
16
  import os
17
- from fastapi import FastAPI
18
- import uvicorn
19
 
20
  # 配置日志
21
  logging.basicConfig(
@@ -24,9 +26,6 @@ logging.basicConfig(
24
  )
25
  logger = logging.getLogger(__name__)
26
 
27
- # FastAPI应用
28
- app = FastAPI()
29
-
30
  class MailGw:
31
  def __init__(self):
32
  self.base_url = "https://api.mail.gw"
@@ -132,20 +131,7 @@ class MailGw:
132
 
133
  logger.error("未能获取到验证码")
134
  return None
135
-
136
- def setup_driver():
137
- """设置Chrome驱动"""
138
- chrome_options = Options()
139
- chrome_options.add_argument('--headless')
140
- chrome_options.add_argument('--no-sandbox')
141
- chrome_options.add_argument('--disable-dev-shm-usage')
142
- chrome_options.binary_location = os.getenv('CHROME_BIN', '/usr/bin/chromium')
143
-
144
- service = Service(os.getenv('CHROMEDRIVER_PATH', '/usr/bin/chromedriver'))
145
- driver = webdriver.Chrome(service=service, options=chrome_options)
146
- return driver
147
-
148
- def get_cookie(driver):
149
  try:
150
  cookie_script = """
151
  var cookieString = document.cookie;
@@ -296,36 +282,93 @@ def registration_process(driver, wait):
296
  cookie = get_cookie(driver)
297
  if cookie:
298
  logger.info("成功获取cookie")
299
- return cookie
300
  else:
301
  logger.error("获取cookie失败")
302
- return None
303
  else:
304
  logger.error("URL未变化为预期值")
305
- return None
306
 
307
  except Exception as e:
308
  logger.error(f"注册过程错误: {str(e)}")
309
- return None
310
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
311
  @app.get("/")
312
- def read_root():
313
  return {"status": "running"}
314
 
315
- @app.get("/generate_cookie")
316
- async def generate_cookie():
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
317
  try:
318
- driver = setup_driver()
319
- wait = WebDriverWait(driver, 20)
320
- cookie = registration_process(driver, wait)
321
- driver.quit()
322
-
323
- if cookie:
324
- return {"status": "success", "cookie": cookie}
325
- else:
326
- return {"status": "error", "message": "Failed to generate cookie"}
327
  except Exception as e:
328
- return {"status": "error", "message": str(e)}
329
 
330
  if __name__ == "__main__":
331
  uvicorn.run(app, host="0.0.0.0", port=7860)
 
6
  from selenium.webdriver.support import expected_conditions as EC
7
  from selenium.common.exceptions import TimeoutException
8
  from selenium.webdriver.common.keys import Keys
9
+ from webdriver_manager.chrome import ChromeDriverManager
10
+ from fastapi import FastAPI, BackgroundTasks
11
+ import uvicorn
12
+ import asyncio
13
  import time
14
  import random
15
  import string
 
18
  import json
19
  import re
20
  import os
 
 
21
 
22
  # 配置日志
23
  logging.basicConfig(
 
26
  )
27
  logger = logging.getLogger(__name__)
28
 
 
 
 
29
  class MailGw:
30
  def __init__(self):
31
  self.base_url = "https://api.mail.gw"
 
131
 
132
  logger.error("未能获取到验证码")
133
  return None
134
+ def get_cookie(driver):
 
 
 
 
 
 
 
 
 
 
 
 
 
135
  try:
136
  cookie_script = """
137
  var cookieString = document.cookie;
 
282
  cookie = get_cookie(driver)
283
  if cookie:
284
  logger.info("成功获取cookie")
285
+ return True
286
  else:
287
  logger.error("获取cookie失败")
288
+ return False
289
  else:
290
  logger.error("URL未变化为预期值")
291
+ return False
292
 
293
  except Exception as e:
294
  logger.error(f"注册过程错误: {str(e)}")
295
+ return False
296
 
297
+ app = FastAPI()
298
+ cookie_generator = None
299
+
300
+ class CookieGenerator:
301
+ def __init__(self):
302
+ self.driver = None
303
+ self.running = False
304
+ self.cookies = []
305
+
306
+ async def start_generation(self):
307
+ if self.running:
308
+ return
309
+
310
+ self.running = True
311
+ try:
312
+ chrome_options = Options()
313
+ chrome_options.add_argument('--headless')
314
+ chrome_options.add_argument('--no-sandbox')
315
+ chrome_options.add_argument('--disable-dev-shm-usage')
316
+ chrome_options.binary_location = os.getenv('CHROME_BIN', '/usr/bin/chromium')
317
+
318
+ service = Service(os.getenv('CHROMEDRIVER_PATH', '/usr/bin/chromedriver'))
319
+ self.driver = webdriver.Chrome(service=service, options=chrome_options)
320
+ wait = WebDriverWait(self.driver, 20)
321
+
322
+ while self.running:
323
+ success = registration_process(self.driver, wait)
324
+ if success:
325
+ logger.info("本次循环成功")
326
+ else:
327
+ logger.error("本次循环失败")
328
+ await asyncio.sleep(5)
329
+
330
+ except Exception as e:
331
+ logger.error(f"Cookie生成错误: {str(e)}")
332
+ finally:
333
+ self.running = False
334
+ if self.driver:
335
+ self.driver.quit()
336
+
337
+ @app.on_event("startup")
338
+ async def startup_event():
339
+ global cookie_generator
340
+ cookie_generator = CookieGenerator()
341
+
342
  @app.get("/")
343
+ async def read_root():
344
  return {"status": "running"}
345
 
346
+ @app.get("/start")
347
+ async def start_generation(background_tasks: BackgroundTasks):
348
+ global cookie_generator
349
+ if not cookie_generator.running:
350
+ background_tasks.add_task(cookie_generator.start_generation)
351
+ return {"status": "started"}
352
+ return {"status": "already running"}
353
+
354
+ @app.get("/stop")
355
+ async def stop_generation():
356
+ global cookie_generator
357
+ if cookie_generator.running:
358
+ cookie_generator.running = False
359
+ return {"status": "stopping"}
360
+ return {"status": "not running"}
361
+
362
+ @app.get("/cookies")
363
+ async def get_cookies():
364
  try:
365
+ if os.path.exists('cookies.txt'):
366
+ with open('cookies.txt', 'r') as file:
367
+ cookies = file.readlines()
368
+ return {"cookies": cookies}
369
+ return {"cookies": []}
 
 
 
 
370
  except Exception as e:
371
+ return {"error": str(e)}
372
 
373
  if __name__ == "__main__":
374
  uvicorn.run(app, host="0.0.0.0", port=7860)