- 登录改为自动填账号密码并勾选用户协议,页面右上角浮层提示人工点「登录」(按钮、滑块/短信、选门店仍人工),登录一次长期复用 - 金色印象 / 金色湖畔各自独立浏览器档案与调试端口(xq0041 / xq0041_b,9222 / 9333),避免同浏览器反复切号触发风控 - 执行模式拆 full(只导金色印象 + 并台账 + 更新核对统计)/ export_only(按范围勾选各导一份,不写表),湖畔报表文件名带「金色湖畔_」前缀;UI 同步重建
163 lines
5.9 KiB
Python
163 lines
5.9 KiB
Python
# -*- coding: utf-8 -*-
|
||
"""浏览器:一次运行共用一个可见浏览器(登录 + 三张表下载都复用它,避免反复开关)。
|
||
|
||
账号档案隔离(见 config.set_company):
|
||
金色印象 用户目录 browser_sessions\\xq0041 调试端口 9222
|
||
金色湖畔 用户目录 browser_sessions\\xq0041_b 调试端口 9333
|
||
两套档案互不共享 Cookie / localStorage,等于两个独立浏览器身份,
|
||
不会出现「同一浏览器里反复切号」那种高风控特征。
|
||
"""
|
||
import os
|
||
import socket
|
||
|
||
from DrissionPage import ChromiumPage, ChromiumOptions
|
||
|
||
from .. import config
|
||
|
||
|
||
def _free_port(base):
|
||
"""从 base 起找一个没被占用的本地端口(避免和别的插件默认 9222 撞上)。"""
|
||
for port in range(base, base + 20):
|
||
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
|
||
s.settimeout(0.2)
|
||
if s.connect_ex(('127.0.0.1', port)) != 0:
|
||
return port
|
||
return base
|
||
|
||
|
||
def open_page(force_login=False):
|
||
co = ChromiumOptions()
|
||
if config.HEADLESS:
|
||
co.headless()
|
||
base_port = config.get_browser_port()
|
||
port = _free_port(base_port)
|
||
try:
|
||
co.set_local_port(port)
|
||
except Exception as e:
|
||
config.log(f'设置调试端口失败(忽略):{e}', 'WARN')
|
||
co.set_argument('--start-maximized')
|
||
co.set_pref('credentials_enable_service', False)
|
||
co.set_pref('profile.password_manager_enabled', False)
|
||
profile = config.get_browser_profile_dir()
|
||
os.makedirs(profile, exist_ok=True)
|
||
co.set_user_data_path(profile)
|
||
config.log(f'{config.company_label()}:浏览器用户目录 {profile},调试端口 {port}'
|
||
+ ('' if port == base_port else f'({base_port} 被占用,已顺延)'), 'DEBUG')
|
||
page = ChromiumPage(co)
|
||
if force_login:
|
||
# 「强制重新登录」:清掉本档案里的 Cookie(不会影响另一家公司)
|
||
try:
|
||
page.set.cookies.clear()
|
||
config.log(f'已清空[{config.company_label()}]浏览器 Cookie(强制重新登录)')
|
||
except Exception as e:
|
||
config.log(f'清空 Cookie 失败(继续按残留登录态走):{e}', 'WARN')
|
||
if not config.HEADLESS:
|
||
# 登录要人工操作(账密/短信/扫码/选商家),全屏 + 置顶避免被其它窗口挡住
|
||
config.apply_window_mode(page)
|
||
return page
|
||
|
||
|
||
def close_page(page):
|
||
try:
|
||
page.quit()
|
||
except Exception:
|
||
pass
|
||
|
||
|
||
def xhr(page, method, url, payload=None):
|
||
"""页面上下文同步 XHR:mtgsig/yodaReady 由页面上的 Yoda(H5guard) SDK 自动补。
|
||
|
||
返回 (status:int, text:str)。
|
||
"""
|
||
import json as _json
|
||
body_js = 'null'
|
||
headers_js = ''
|
||
if payload is not None:
|
||
body_js = 'JSON.stringify(' + _json.dumps(payload, ensure_ascii=False) + ')'
|
||
headers_js = "x.setRequestHeader('Content-Type','application/json');"
|
||
js = '''
|
||
try {
|
||
var x = new XMLHttpRequest();
|
||
x.open('%s', '%s', false);
|
||
x.withCredentials = true;
|
||
%s
|
||
x.send(%s);
|
||
return x.status + '||' + String(x.responseText || '');
|
||
} catch (e) {
|
||
return 'ERR||' + e;
|
||
}
|
||
''' % (method.upper(), url, headers_js, body_js)
|
||
raw = page.run_js(js)
|
||
if not raw or '||' not in str(raw):
|
||
return 0, f'返回值异常:{str(raw)[:200]}'
|
||
status, _, text = str(raw).partition('||')
|
||
try:
|
||
return int(status), text
|
||
except Exception:
|
||
return 0, text
|
||
|
||
|
||
def api_json(page, method, url, payload=None):
|
||
import json as _json
|
||
status, text = xhr(page, method, url, payload)
|
||
name = url.split('/')[-1].split('?')[0]
|
||
if status != 200:
|
||
config.log(f'{name} 请求失败:status={status} {text[:200]}', 'WARN')
|
||
return None
|
||
try:
|
||
return _json.loads(text)
|
||
except Exception as e:
|
||
config.log(f'{name} 返回非 JSON:{e} | {text[:200]}', 'WARN')
|
||
return None
|
||
|
||
|
||
def download_file(link, save_path):
|
||
"""S3 预签名 URL 直下(无需 Cookie / mtgsig)。返回字节数,失败 0。"""
|
||
import os
|
||
import time
|
||
|
||
import requests
|
||
|
||
headers = {
|
||
'User-Agent': ('Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 '
|
||
'(KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36'),
|
||
'Accept': '*/*',
|
||
}
|
||
os.makedirs(os.path.dirname(save_path), exist_ok=True)
|
||
for attempt in range(1, config.RETRY_MAX + 1):
|
||
try:
|
||
resp = requests.get(link, headers=headers, timeout=300, stream=True)
|
||
if resp.status_code != 200:
|
||
config.log(f'下载失败:HTTP {resp.status_code}({attempt}/{config.RETRY_MAX})', 'WARN')
|
||
time.sleep(2)
|
||
continue
|
||
tmp = save_path + '.part'
|
||
with open(tmp, 'wb') as f:
|
||
for chunk in resp.iter_content(128 * 1024):
|
||
if chunk:
|
||
f.write(chunk)
|
||
os.replace(tmp, save_path)
|
||
size = os.path.getsize(save_path)
|
||
if size < 1024:
|
||
config.log(f'文件异常小({size} 字节),重试 {attempt}/{config.RETRY_MAX}', 'WARN')
|
||
time.sleep(2)
|
||
continue
|
||
return size
|
||
except Exception as e:
|
||
config.log(f'下载异常:{e}({attempt}/{config.RETRY_MAX})', 'WARN')
|
||
time.sleep(2)
|
||
return 0
|
||
|
||
|
||
def read_xlsx_summary(path):
|
||
"""读 sheet 名/行列数,确认文件有效。"""
|
||
try:
|
||
from openpyxl import load_workbook
|
||
wb = load_workbook(path, read_only=True, data_only=True)
|
||
ws = wb.worksheets[0]
|
||
info = {'sheet': ws.title, 'rows': ws.max_row, 'cols': ws.max_column}
|
||
wb.close()
|
||
return info
|
||
except Exception as e:
|
||
return {'error': str(e)}
|