Files
37duAutomation/workflows/share/erp_login.py
T

275 lines
11 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
# -*- coding: utf-8 -*-
"""
@FileName: erp_login.py
@Description: 金蝶 K3Cloud(HTML5)ERP 登录模块,兼容新旧两套 ERP 站点。
通过函数参数传入新旧系统标识(或完整 URL)与账号密码,
实现登录不同系统。供各影刀业务脚本复用。
登录页元素(新旧版一致):
用户名输入框 <input id="user" placeholder="用户名">
密码输入框 <input id="password" type="password">(新rsa可见框为 #password)
登录按钮 <button id="btnLogin" class="btnlogin k-button">登录</button>
登录成功判定:URL 包含 /k3cloud/html5/dform.aspx 即视为登录成功。
特殊弹窗:登录时若弹出「该帐号已登录在线,确认让对方下线」警告框,
自动点击蓝色「确认」按钮(.BlueButtonStyle,id 为动态 UUID 不可定位)。
配置(可选,仅作为参数未传时的兜底,从项目根 .env 读取):
erp_login_username=默认用户名
erp_login_password=默认密码
依赖(影刀「Python包管理」安装):
pip install DrissionPage python-dotenv
入口:
erp_login(erp='old'|'new'|完整URL, username=None, password=None,
headless=False, cookie_file=None)
-> (bool, ChromiumPage) 登录成功返回 (True, 已登录的页面对象)
直接运行 python erp_login.py 自测(测试账号在 __main__ 内的变量中修改)
"""
import os
import sys
import time
import json
from DrissionPage import ChromiumPage, ChromiumOptions
from dotenv import load_dotenv
# ================== 站点定义(新旧 ERP) ==================
ERP_URLS = {
'old': 'https://erp.37du.co/k3cloud/html5/index.aspx',
'new': 'https://criterion.erp.37du.co/k3cloud/html5/index.aspx',
}
# 登录页元素定位(新旧版元素 id 一致)
USER_INPUT = '#user'
PWD_INPUT = '#password'
LOGIN_BTN = '#btnLogin'
# 「该帐号已登录在线」弹窗的确认按钮(蓝色样式 class 固定,id 为动态 UUID)
KICK_CONFIRM_BTN = 'css:.k-window .BlueButtonStyle'
# 登录成功标志:URL 包含该关键字即视为登录成功(跳转到默认表单页)
SUCCESS_KEYWORD = '/k3cloud/html5/dform.aspx'
# ================== 全局配置 ==================
RETRY_MAX = 3 # 全局重试次数(项目规范:最多 3 次)
TIMEOUT = 10 # 元素等待超时(秒)
LOGIN_WAIT = 3 # 点击登录后等待(秒)
HEADLESS = False # 是否无头模式
# 项目根目录 .env(workflows/ 影刀脚本统一使用根 .env)
_root_env = os.path.join(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))), '.env')
if os.path.exists(_root_env):
load_dotenv(_root_env)
load_dotenv()
def _resolve_url(erp):
"""把 'old'/'new'/完整URL 统一解析为登录页 URL。"""
if erp in ERP_URLS:
return ERP_URLS[erp]
if erp and erp.lower().startswith('http'):
return erp
raise ValueError(f"无效的 ERP 标识:{erp},可选 'old'、'new' 或完整登录页 URL")
def _is_login_page(url):
"""判断当前 URL 是否仍停留在登录页。"""
return 'index.aspx' in (url or '').lower()
def _is_login_success(url):
"""登录成功判定:URL 包含 dform.aspx 即视为已登录。"""
return SUCCESS_KEYWORD in (url or '')
def _handle_kick_dialog(page):
"""处理「该帐号已登录在线,确认让对方下线」弹窗:存在则点击蓝色确认按钮。
返回是否点击了确认。"""
for _ in range(3):
btn = page.ele(KICK_CONFIRM_BTN, timeout=2)
if not btn:
return False
try:
btn.click()
print("[ERP登录] 检测到「已登录在线」弹窗,点击确认(让对方下线)")
return True
except Exception as e:
print(f"[ERP登录] 点击弹窗确认异常:{e}")
time.sleep(1)
return False
def _save_cookies(page, path):
"""保存当前浏览器 cookies 到 json 文件。"""
if not path:
return False
try:
os.makedirs(os.path.dirname(os.path.abspath(path)), exist_ok=True)
with open(path, 'w', encoding='utf-8') as f:
json.dump(page.cookies(), f, ensure_ascii=False, indent=2)
print(f"[ERP登录] 已保存 cookie → {path}")
return True
except Exception as e:
print(f"[ERP登录] 保存 cookie 失败:{e}")
return False
def _load_cookies(page, path):
"""把 json 文件中的 cookies 注入浏览器(供已有登录态复用)。"""
if not path or not os.path.exists(path):
return False
try:
with open(path, 'r', encoding='utf-8') as f:
cookies = json.load(f)
if not cookies:
return False
page.set.cookies(cookies)
print(f"[ERP登录] 已注入 cookie({len(cookies)} 条)")
return True
except Exception as e:
print(f"[ERP登录] 注入 cookie 失败:{e}")
return False
def erp_login(erp='old', username=None, password=None, headless=None, cookie_file=None,
debug_port=None, user_data_path=None, close_on_fail=True):
"""
登录金蝶 K3Cloud ERP(新旧系统通用)。
参数:
erp 'old' 旧版 erp.37du.co / 'new' 新版 criterion.erp.37du.co / 完整登录页 URL
username 用户名;不传则读项目根 .env 的 erp_login_username
password 密码;不传则读项目根 .env 的 erp_login_password
headless 是否无头;不传用模块默认 HEADLESS
cookie_file cookies 保存/复用的 json 文件路径:
- 存在时先注入,若登录态有效直接复用(免登录)
- 登录成功后将最新 cookies 回写,供下次复用
debug_port 固定调试端口:传了则复用已在该端口运行的浏览器(不重复登录)
user_data_path 固定浏览器 profile 目录:持久化登录态;配合 debug_port
实现「脚本结束不关浏览器、下次直接复用」的调试模式
close_on_fail 登录失败时是否关闭浏览器。调试复用模式下传 False,
避免误关共享浏览器实例(默认 True)
返回:
(success, page) success=True 时 page 为已登录的 ChromiumPage;
失败时 page 为 None(浏览器已关闭)。调用方负责后续 page.quit()。
"""
login_url = _resolve_url(erp)
username = username or os.getenv('erp_login_username', '')
password = password or os.getenv('erp_login_password', '')
if not (username and password):
print("登录配置缺失:未传 username/password 且 .env 未配置 erp_login_username/erp_login_password")
return False, None
headless = HEADLESS if headless is None else bool(headless)
for attempt in range(1, RETRY_MAX + 1):
page = None
try:
print(f"[ERP登录] 第 {attempt}/{RETRY_MAX} 次 → {login_url}")
co = ChromiumOptions()
if headless:
co.headless()
if debug_port:
co.set_local_port(debug_port)
if user_data_path:
os.makedirs(user_data_path, exist_ok=True)
co.set_user_data_path(user_data_path)
page = ChromiumPage(co)
# ---- 复用已有登录态(避免重复登录/重复跳转)----
# 1) 当前标签页已是 ERP 主界面 → 直接复用
cur_url = (page.url or '').strip()
if _is_login_success(cur_url):
print(f"[ERP登录] 当前标签页已是主界面,直接复用 → {cur_url}")
_save_cookies(page, cookie_file)
return True, page
# 2) 浏览器里已打开 ERP 主界面标签页(只是当前激活的是其它标签页)→ 切换复用
try:
tabs = page.get_tabs(url=SUCCESS_KEYWORD)
except Exception:
tabs = []
if tabs:
try:
page.activate_tab(tabs[0])
print(f"[ERP登录] 已切换到已有 ERP 主界面标签页,直接复用 → {tabs[0].url}")
except Exception as e:
print(f"[ERP登录] 切换已有标签页异常:{e}")
_save_cookies(page, cookie_file)
return True, page
# 3) 都没有才走 cookie 注入 + 免登录跳转
_load_cookies(page, cookie_file)
page.get(login_url)
time.sleep(2)
# 已有登录态(cookie 有效)会自动跳转到主界面
if not _is_login_page(page.url):
print("[ERP登录] 已有登录态,直接复用")
_save_cookies(page, cookie_file)
return True, page
user = page.ele(USER_INPUT, timeout=TIMEOUT)
if not user:
print("[ERP登录] 找不到用户名输入框")
continue
user.clear()
user.input(username)
time.sleep(0.5)
# 用户名框是 autocomplete 控件,需按回车关闭弹出的下拉提示框
page.actions.key_down('Enter')
page.actions.key_up('Enter')
time.sleep(0.3)
pwd = page.ele(PWD_INPUT, timeout=TIMEOUT)
if not pwd:
print("[ERP登录] 找不到密码输入框")
continue
pwd.clear()
pwd.input(password)
time.sleep(0.3)
btn = page.ele(LOGIN_BTN, timeout=TIMEOUT)
if not btn:
print("[ERP登录] 找不到登录按钮")
continue
btn.click()
# 登录后轮询:处理「已登录在线」弹窗 + 等待跳转到 dform.aspx
for _ in range(6):
time.sleep(LOGIN_WAIT)
if _is_login_success(page.url):
print(f"[ERP登录] 登录成功 → {page.url}")
_save_cookies(page, cookie_file)
return True, page
_handle_kick_dialog(page)
print("[ERP登录] 点击登录后未跳转到 dform.aspx(账号密码错误或网络异常)")
except Exception as e:
print(f"[ERP登录] 异常:{e}")
# 走到这里说明本轮失败,关闭浏览器后重试(成功时在上方已直接 return)
if page is not None and close_on_fail:
try:
page.quit()
except Exception:
pass
time.sleep(1)
print("[ERP登录] 重试 3 次均失败")
return False, None
def main(erp='old', username=None, password=None):
ok, page = erp_login(erp, username, password)
if ok:
input("登录成功,按回车关闭浏览器...")
page.quit()
else:
sys.exit(1)
if __name__ == '__main__':
main("new", username="蒋辉", password="***REMOVED***")