[Python] 纯文本查看 复制代码
from django.http import JsonResponse
from django.views.decorators.csrf import csrf_exempt
import json
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.chrome.options import Options
from selenium.common.exceptions import NoSuchElementException, TimeoutException
from webdriver_manager.chrome import ChromeDriverManager
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
# 初始化 WebDriver
def initialize_login_driver():
chrome_options = Options()
chrome_options.add_argument("--start-maximized")
chrome_options.add_argument("--disable-extensions")
chrome_options.add_argument("--disable-popup-blocking")
chrome_options.add_argument("--disable-infobars")
chrome_options.add_argument("--disable-notifications")
chrome_options.add_experimental_option("useAutomationExtension", False)
chrome_options.add_experimental_option("detach", True) # 保持浏览器打开
# chrome_options.add_argument("--headless") # Uncomment if you want headless mode
driver = webdriver.Chrome(service=Service(ChromeDriverManager().install()), options=chrome_options)
return driver
def initialize_password_driver():
chrome_options = Options()
chrome_options.add_argument("--start-maximized")
chrome_options.add_argument("--disable-extensions")
chrome_options.add_argument("--disable-popup-blocking")
chrome_options.add_argument("--disable-infobars")
chrome_options.add_argument("--disable-notifications")
chrome_options.add_experimental_option("useAutomationExtension", False)
chrome_options.add_experimental_option("detach", True) # 保持浏览器打开
# chrome_options.add_argument("--headless") # Uncomment if you want headless mode
driver = webdriver.Chrome(service=Service(ChromeDriverManager().install()), options=chrome_options)
return driver
def login_to_gitlab(driver, url, username, password):
try:
driver.get(url)
wait = WebDriverWait(driver, 10)
username_input = wait.until(EC.presence_of_element_located((By.ID, 'user_login')))
password_input = wait.until(EC.presence_of_element_located((By.ID, 'user_password')))
username_input.clear()
username_input.send_keys(username)
password_input.clear()
password_input.send_keys(password)
login_button = wait.until(EC.element_to_be_clickable((By.XPATH, '//button[@type="submit"]')))
login_button.click()
wait.until(EC.presence_of_element_located((By.CLASS_NAME, 'mobile-overlay')))
return {"message": "Login successful"}
except TimeoutException:
return {"error": "Timeout waiting for elements"}
except NoSuchElementException:
return {"error": "Element not found"}
except Exception as e:
return {"error": str(e)}
finally:
return {"message": "Login successful"}
# driver.quit()
@csrf_exempt
def login_view(request):
if request.method == 'POST':
try:
data = json.loads(request.body)
login_type = data.get('type')
url = data.get('url')
username = data.get('username')
password = data.get('password')
if not url or not username or not password:
return JsonResponse({"error": "Missing URL, username, or password"}, status=400)
driver = initialize_login_driver()
if login_type == "gitlab":
result = login_to_gitlab(driver, url, username, password)
return JsonResponse(result)
except json.JSONDecodeError:
return JsonResponse({"error": "Invalid JSON"}, status=400)
else:
return JsonResponse({"error": "Only POST method allowed"}, status=400)
@csrf_exempt
def reset_password(request):
if request.method == 'POST':
try:
data = json.loads(request.body)
reset_type = data.get('type')
login_url = data.get('url')
update_password_url = data.get("password_url")
username = data.get('username')
password = data.get('password')
new_password = data.get("new_password")
if not login_url or not username or not password:
return JsonResponse({"error": "Missing URL, username, or password"}, status=400)
driver = initialize_password_driver()
if reset_type == "gitlab":
result = reset_to_gitlab(driver, login_url, username, password,update_password_url,new_password)
return JsonResponse(result)
except json.JSONDecodeError:
return JsonResponse({"error": "Invalid JSON"}, status=400)
else:
return JsonResponse({"error": "Only POST method allowed"}, status=400)
def reset_to_gitlab(driver, url, username, password, update_url, new_pwd):
try:
print("Navigating to login page...")
driver.get(url)
wait = WebDriverWait(driver, 10)
# 登录操作
print("Looking for username input field...")
username_input = wait.until(EC.presence_of_element_located((By.ID, 'user_login')))
print("Found username input field.")
print("Looking for password input field...")
password_input = wait.until(EC.presence_of_element_located((By.ID, 'user_password')))
print("Found password input field.")
username_input.clear()
username_input.send_keys(username)
password_input.clear()
password_input.send_keys(password)
print("Looking for login button...")
login_button = wait.until(EC.element_to_be_clickable((By.XPATH, '//button[@type="submit"]')))
print("Found login button, clicking...")
login_button.click()
print("Waiting for page to load after login...")
wait.until(EC.presence_of_element_located((By.CLASS_NAME, 'mobile-overlay')))
print("Login successful, navigating to update password page...")
# 跳转到修改密码页面
driver.get(update_url)
print(f"Navigated to {update_url}, waiting for password fields...")
# 等待密码修改页面元素加载
wait.until(EC.presence_of_element_located((By.ID, 'user_password')))
print("Found old password field.")
# 修改密码
old_pwd_input = driver.find_element(By.ID, 'user_password')
print("Found old password input field.")
new_password_input = driver.find_element(By.ID, 'user_new_password')
print("Found new password input field.")
user_password_confirmation = driver.find_element(By.ID, 'user_password_confirmation')
print("Found password confirmation input field.")
old_pwd_input.clear()
old_pwd_input.send_keys(password)
new_password_input.clear()
new_password_input.send_keys(new_pwd)
user_password_confirmation.clear()
user_password_confirmation.send_keys(new_pwd)
print("Password updated successfully.")
return {"message": "Password updated successfully"}
except TimeoutException:
print("Timeout waiting for elements")
return {"error": "Timeout waiting for elements"}
except NoSuchElementException:
print("Element not found")
return {"error": "Element not found"}
except Exception as e:
print(f"An error occurred: {str(e)}")
return {"error": str(e)}
# finally:
# driver.get(update_url)
# driver.quit()