-
Notifications
You must be signed in to change notification settings - Fork 118
Expand file tree
/
Copy pathDrissionPage_example.py
More file actions
1237 lines (1040 loc) · 41.2 KB
/
DrissionPage_example.py
File metadata and controls
1237 lines (1040 loc) · 41.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
from DrissionPage import Chromium, ChromiumOptions
from DrissionPage.errors import PageDisconnectedError
import argparse
import shutil
import tempfile
import datetime
import logging
import time
import os
import secrets
import sys
from email_register import get_email_and_token, get_oai_code
def setup_run_logger() -> logging.Logger:
log_dir = os.path.join(os.path.dirname(__file__), "logs")
os.makedirs(log_dir, exist_ok=True)
ts = datetime.datetime.now().strftime("%Y%m%d_%H%M%S")
log_path = os.path.join(log_dir, f"run_{ts}.log")
logger = logging.getLogger("grok_register")
logger.setLevel(logging.INFO)
logger.handlers.clear()
fmt = logging.Formatter("%(asctime)s | %(message)s", datefmt="%Y-%m-%d %H:%M:%S")
fh = logging.FileHandler(log_path, encoding="utf-8")
fh.setFormatter(fmt)
logger.addHandler(fh)
sh = logging.StreamHandler(sys.stdout)
sh.setFormatter(fmt)
logger.addHandler(sh)
logger.info("日志文件: %s", log_path)
return logger
run_logger: logging.Logger = None
def ensure_stable_python_runtime():
# 优先自动切到更稳定的 3.12 / 3.13,避免 3.14 下 Mail.tm 偶发 TLS/兼容问题。
if sys.version_info < (3, 14) or os.environ.get("DPE_REEXEC_DONE") == "1":
return
local_app_data = os.environ.get("LOCALAPPDATA", "")
candidates = [
os.path.join(local_app_data, "Programs", "Python", "Python312", "python.exe"),
os.path.join(local_app_data, "Programs", "Python", "Python313", "python.exe"),
]
current_python = os.path.normcase(os.path.abspath(sys.executable))
for candidate in candidates:
if not os.path.isfile(candidate):
continue
if os.path.normcase(os.path.abspath(candidate)) == current_python:
return
print(f"[*] 检测到 Python {sys.version.split()[0]},自动切换到更稳定的解释器: {candidate}")
env = os.environ.copy()
env["DPE_REEXEC_DONE"] = "1"
os.execve(candidate, [candidate, os.path.abspath(__file__), *sys.argv[1:]], env)
def warn_runtime_compatibility():
# 中文提示:避免把底层 TLS 兼容问题误判成脚本逻辑错误。
if sys.version_info >= (3, 14):
print("[提示] 当前 Python 为 3.14+;若出现 Mail.tm TLS 异常,建议改用 Python 3.12 或 3.13。")
ensure_stable_python_runtime()
warn_runtime_compatibility()
# 无头服务器自动启用 Xvfb 虚拟显示器
_virtual_display = None
if not os.environ.get("DISPLAY") or os.environ.get("USE_XVFB") == "1":
try:
from pyvirtualdisplay import Display
_virtual_display = Display(visible=0, size=(1920, 1080))
_virtual_display.start()
print(f"[*] Xvfb 虚拟显示器已启动: {os.environ.get('DISPLAY')}")
except Exception as e:
print(f"[Warn] Xvfb 启动失败: {e},将尝试直接运行")
co = ChromiumOptions()
co.auto_port()
co.set_argument("--no-sandbox")
co.set_argument("--disable-gpu")
co.set_argument("--disable-dev-shm-usage")
co.set_argument("--disable-software-rasterizer")
# 从 config.json 读取代理配置给浏览器
_browser_proxy = ""
try:
import json as _json_mod
_cfg_path = os.path.join(os.path.dirname(__file__), "config.json")
if os.path.isfile(_cfg_path):
with open(_cfg_path, "r") as _f:
_cfg = _json_mod.load(_f)
_browser_proxy = str(_cfg.get("browser_proxy", "") or _cfg.get("proxy", "") or "")
except Exception:
pass
if _browser_proxy:
co.set_proxy(_browser_proxy)
print(f"[*] 浏览器代理: {_browser_proxy}")
# Linux 服务器自动检测 chromium 路径
import platform
import shutil
import glob as _glob_mod
if platform.system() == "Linux":
# 优先用 playwright 装的 chromium(无 AppArmor 限制)
_pw_chromes = _glob_mod.glob(os.path.expanduser("~/.cache/ms-playwright/chromium-*/chrome-linux*/chrome"))
if _pw_chromes:
co.set_browser_path(_pw_chromes[0])
else:
for _candidate in ["/usr/bin/chromium-browser", "/usr/bin/chromium", "/usr/bin/google-chrome"]:
if os.path.isfile(_candidate):
co.set_browser_path(_candidate)
break
# user_data_path 在 start_browser() 每轮动态设置,此处不固定
co.set_timeouts(base=1)
# 加载修复 MouseEvent.screenX / screenY 的扩展。
EXTENSION_PATH = os.path.abspath(os.path.join(os.path.dirname(__file__), "turnstilePatch"))
co.add_extension(EXTENSION_PATH)
_chrome_temp_dir: str = ""
browser = None
page = None
SIGNUP_URL = "https://accounts.x.ai/sign-up?redirect=grok-com"
_sso_dir = os.path.join(os.path.dirname(__file__), "sso")
_sso_ts = datetime.datetime.now().strftime("%Y%m%d_%H%M%S")
DEFAULT_SSO_FILE = os.path.join(_sso_dir, f"sso_{_sso_ts}.txt")
def start_browser():
# 每轮从全新浏览器开始,使用独立临时 profile 目录避免 Cookie/Session 复用。
global browser, page, _chrome_temp_dir
_chrome_temp_dir = tempfile.mkdtemp(prefix="chrome_run_")
co.set_user_data_path(_chrome_temp_dir)
browser = Chromium(co)
tabs = browser.get_tabs()
page = tabs[-1] if tabs else browser.new_tab()
return browser, page
def stop_browser():
# 完整关闭整个浏览器实例,并清理本轮临时 profile,供下一轮重新拉起。
global browser, page, _chrome_temp_dir
if browser is not None:
try:
browser.quit()
except Exception:
pass
browser = None
page = None
if _chrome_temp_dir and os.path.isdir(_chrome_temp_dir):
shutil.rmtree(_chrome_temp_dir, ignore_errors=True)
_chrome_temp_dir = ""
def restart_browser():
# 清除 cookie/storage 代替完整重启,节省 Chrome 冷启动时间。
global browser, page
if browser is None:
start_browser()
return
try:
tabs = browser.get_tabs()
page = tabs[-1] if tabs else browser.new_tab()
page.run_js("window.localStorage.clear(); window.sessionStorage.clear();")
page.clear_cache(session_storage=True, cookies=True)
except Exception:
stop_browser()
start_browser()
def refresh_active_page():
# 验证码确认后页面会跳转,旧 page 句柄可能断开,这里统一重新获取当前活动标签页。
global browser, page
if browser is None:
start_browser()
try:
tabs = browser.get_tabs()
if tabs:
page = tabs[-1]
else:
page = browser.new_tab()
except Exception:
restart_browser()
return page
def open_signup_page():
# 每轮开始时打开注册页,并切到“使用邮箱注册”流程。
global page
refresh_active_page()
try:
page.get(SIGNUP_URL)
except Exception:
refresh_active_page()
page = browser.new_tab(SIGNUP_URL)
click_email_signup_button()
def close_current_page():
# 兼容旧调用名,实际行为改为整轮重启浏览器。
restart_browser()
def has_profile_form():
# 最终注册页只要出现姓名和密码输入框,就认为已经成功进入资料填写阶段。
refresh_active_page()
try:
return bool(page.run_js(
"""
const givenInput = document.querySelector('input[data-testid="givenName"], input[name="givenName"], input[autocomplete="given-name"]');
const familyInput = document.querySelector('input[data-testid="familyName"], input[name="familyName"], input[autocomplete="family-name"]');
const passwordInput = document.querySelector('input[data-testid="password"], input[name="password"], input[type="password"]');
return !!(givenInput && familyInput && passwordInput);
"""
))
except Exception:
return False
def click_email_signup_button(timeout=10):
# 页面打开后,自动点击“使用邮箱注册”按钮。
deadline = time.time() + timeout
while time.time() < deadline:
clicked = page.run_js(r"""
const candidates = Array.from(document.querySelectorAll('button, a, [role="button"]'));
const target = candidates.find((node) => {
const text = (node.innerText || node.textContent || '').replace(/\s+/g, '').toLowerCase();
return text.includes('使用邮箱注册') || text.includes('signupwithemail') || text.includes('signupemail') || text.includes('continuewith email') || text.includes('email');
});
if (!target) {
return false;
}
target.click();
return true;
""")
if clicked:
return True
time.sleep(0.5)
raise Exception('未找到“使用邮箱注册”按钮')
def fill_email_and_submit(timeout=15):
# 复用 `email_register.py` 里的邮箱获取逻辑,保留邮箱与 token 供后续验证码步骤继续使用。
email, dev_token = get_email_and_token()
if not email or not dev_token:
raise Exception("获取邮箱失败")
deadline = time.time() + timeout
while time.time() < deadline:
filled = page.run_js(
"""
const email = arguments[0];
function isVisible(node) {
if (!node) {
return false;
}
const style = window.getComputedStyle(node);
if (style.display === 'none' || style.visibility === 'hidden' || style.opacity === '0') {
return false;
}
const rect = node.getBoundingClientRect();
return rect.width > 0 && rect.height > 0;
}
const input = Array.from(document.querySelectorAll('input[data-testid="email"], input[name="email"], input[type="email"], input[autocomplete="email"]')).find((node) => {
return isVisible(node) && !node.disabled && !node.readOnly;
}) || null;
if (!input) {
return 'not-ready';
}
input.focus();
input.click();
// 不能只写 `input.value = xxx`,否则 React / 受控表单可能没有同步内部状态。
const valueSetter = Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, 'value')?.set;
const tracker = input._valueTracker;
if (tracker) {
tracker.setValue('');
}
if (valueSetter) {
valueSetter.call(input, email);
} else {
input.value = email;
}
input.dispatchEvent(new InputEvent('beforeinput', {
bubbles: true,
data: email,
inputType: 'insertText',
}));
input.dispatchEvent(new InputEvent('input', {
bubbles: true,
data: email,
inputType: 'insertText',
}));
input.dispatchEvent(new Event('change', { bubbles: true }));
if ((input.value || '').trim() !== email || !input.checkValidity()) {
return false;
}
input.blur();
return 'filled';
""",
email,
)
if filled == 'not-ready':
time.sleep(0.5)
continue
if filled != 'filled':
print(f"[Debug] 邮箱输入框已出现,但写入失败: {filled}")
time.sleep(0.5)
continue
if filled == 'filled':
time.sleep(0.8)
clicked = page.run_js(
r"""
function isVisible(node) {
if (!node) {
return false;
}
const style = window.getComputedStyle(node);
if (style.display === 'none' || style.visibility === 'hidden' || style.opacity === '0') {
return false;
}
const rect = node.getBoundingClientRect();
return rect.width > 0 && rect.height > 0;
}
const input = Array.from(document.querySelectorAll('input[data-testid="email"], input[name="email"], input[type="email"], input[autocomplete="email"]')).find((node) => {
return isVisible(node) && !node.disabled && !node.readOnly;
}) || null;
if (!input || !input.checkValidity() || !(input.value || '').trim()) {
return false;
}
const buttons = Array.from(document.querySelectorAll('button[type="submit"], button')).filter((node) => {
return isVisible(node) && !node.disabled && node.getAttribute('aria-disabled') !== 'true';
});
const submitButton = buttons.find((node) => {
const text = (node.innerText || node.textContent || '').replace(/\s+/g, '');
const t = text.toLowerCase(); return text === '注册' || text.includes('注册') || t === 'signup' || t === 'sign up' || t.includes('sign up');
});
if (!submitButton || submitButton.disabled) {
return false;
}
submitButton.click();
return true;
"""
)
if clicked:
print(f"[*] 已填写邮箱并点击注册: {email}")
return email, dev_token
time.sleep(0.5)
raise Exception("未找到邮箱输入框或注册按钮")
def fill_code_and_submit(email, dev_token, timeout=60):
# 复用 `email_register.py` 里的验证码轮询逻辑,等待邮件到达后自动填写 OTP。
code = get_oai_code(dev_token, email)
if not code:
raise Exception("获取验证码失败")
deadline = time.time() + timeout
while time.time() < deadline:
try:
filled = page.run_js(
"""
const code = String(arguments[0] || '').trim();
function isVisible(node) {
if (!node) {
return false;
}
const style = window.getComputedStyle(node);
if (style.display === 'none' || style.visibility === 'hidden' || style.opacity === '0') {
return false;
}
const rect = node.getBoundingClientRect();
return rect.width > 0 && rect.height > 0;
}
function setNativeValue(input, value) {
const nativeInputValueSetter = Object.getOwnPropertyDescriptor(window.HTMLInputElement.prototype, 'value')?.set;
const tracker = input._valueTracker;
if (tracker) {
tracker.setValue('');
}
if (nativeInputValueSetter) {
nativeInputValueSetter.call(input, '');
nativeInputValueSetter.call(input, value);
} else {
input.value = '';
input.value = value;
}
}
function dispatchInputEvents(input, value) {
input.dispatchEvent(new InputEvent('beforeinput', {
bubbles: true,
cancelable: true,
data: value,
inputType: 'insertText',
}));
input.dispatchEvent(new InputEvent('input', {
bubbles: true,
cancelable: true,
data: value,
inputType: 'insertText',
}));
input.dispatchEvent(new Event('change', { bubbles: true }));
}
const input = Array.from(document.querySelectorAll('input[data-input-otp="true"], input[name="code"], input[autocomplete="one-time-code"], input[inputmode="numeric"], input[inputmode="text"]')).find((node) => {
return isVisible(node) && !node.disabled && !node.readOnly && Number(node.maxLength || code.length || 6) > 1;
}) || null;
const otpBoxes = Array.from(document.querySelectorAll('input')).filter((node) => {
if (!isVisible(node) || node.disabled || node.readOnly) {
return false;
}
const maxLength = Number(node.maxLength || 0);
const autocomplete = String(node.autocomplete || '').toLowerCase();
return maxLength === 1 || autocomplete === 'one-time-code';
});
if (!input && otpBoxes.length < code.length) {
return 'not-ready';
}
if (input) {
input.focus();
input.click();
setNativeValue(input, code);
dispatchInputEvents(input, code);
const normalizedValue = String(input.value || '').trim();
const expectedLength = Number(input.maxLength || code.length || 6);
const slots = Array.from(document.querySelectorAll('[data-input-otp-slot="true"]'));
const filledSlots = slots.filter((slot) => (slot.textContent || '').trim()).length;
if (normalizedValue !== code) {
return 'aggregate-mismatch';
}
if (expectedLength > 0 && normalizedValue.length !== expectedLength) {
return 'aggregate-length-mismatch';
}
if (slots.length && filledSlots && filledSlots !== normalizedValue.length) {
return 'aggregate-slot-mismatch';
}
input.blur();
return 'filled';
}
const orderedBoxes = otpBoxes.slice(0, code.length);
for (let i = 0; i < orderedBoxes.length; i += 1) {
const box = orderedBoxes[i];
const char = code[i] || '';
box.focus();
box.click();
setNativeValue(box, char);
dispatchInputEvents(box, char);
box.dispatchEvent(new KeyboardEvent('keydown', { bubbles: true, key: char }));
box.dispatchEvent(new KeyboardEvent('keyup', { bubbles: true, key: char }));
box.blur();
}
const merged = orderedBoxes.map((node) => String(node.value || '').trim()).join('');
return merged === code ? 'filled' : 'box-mismatch';
""",
code,
)
except PageDisconnectedError:
# 点击确认邮箱后如果刚好发生跳转,旧页面句柄会断开;此时切到新页继续判断即可。
refresh_active_page()
if has_profile_form():
print("[*] 验证码提交后已跳转到最终注册页。")
return code
time.sleep(1)
continue
if filled == 'not-ready':
if has_profile_form():
print("[*] 已直接进入最终注册页,跳过验证码按钮确认。")
return code
time.sleep(0.5)
continue
if filled != 'filled':
print(f"[Debug] 验证码输入框已出现,但写入失败: {filled}")
time.sleep(0.5)
continue
if filled == 'filled':
time.sleep(1.2)
try:
clicked = page.run_js(
r"""
function isVisible(node) {
if (!node) {
return false;
}
const style = window.getComputedStyle(node);
if (style.display === 'none' || style.visibility === 'hidden' || style.opacity === '0') {
return false;
}
const rect = node.getBoundingClientRect();
return rect.width > 0 && rect.height > 0;
}
const aggregateInput = Array.from(document.querySelectorAll('input[data-input-otp="true"], input[name="code"], input[autocomplete="one-time-code"], input[inputmode="numeric"], input[inputmode="text"]')).find((node) => {
return isVisible(node) && !node.disabled && !node.readOnly && Number(node.maxLength || 0) > 1;
}) || null;
let value = '';
if (aggregateInput) {
value = String(aggregateInput.value || '').trim();
const expectedLength = Number(aggregateInput.maxLength || value.length || 6);
if (!value || (expectedLength > 0 && value.length !== expectedLength)) {
return false;
}
const slots = Array.from(document.querySelectorAll('[data-input-otp-slot="true"]'));
if (slots.length) {
const filledSlots = slots.filter((slot) => (slot.textContent || '').trim()).length;
if (filledSlots && filledSlots !== value.length) {
return false;
}
}
} else {
const otpBoxes = Array.from(document.querySelectorAll('input')).filter((node) => {
if (!isVisible(node) || node.disabled || node.readOnly) {
return false;
}
const maxLength = Number(node.maxLength || 0);
const autocomplete = String(node.autocomplete || '').toLowerCase();
return maxLength === 1 || autocomplete === 'one-time-code';
});
value = otpBoxes.map((node) => String(node.value || '').trim()).join('');
if (!value || value.length < 6) {
return false;
}
}
const buttons = Array.from(document.querySelectorAll('button[type="submit"], button')).filter((node) => {
return isVisible(node) && !node.disabled && node.getAttribute('aria-disabled') !== 'true';
});
const confirmButton = buttons.find((node) => {
const text = (node.innerText || node.textContent || '').replace(/\s+/g, '');
const t = text.toLowerCase(); return text === '确认邮箱' || text.includes('确认邮箱') || text === '继续' || text.includes('继续') || text === '下一步' || text.includes('下一步') || t.includes('confirm') || t.includes('continue') || t.includes('next') || t.includes('verify');
});
if (!confirmButton) {
return 'no-button';
}
confirmButton.focus();
confirmButton.click();
return 'clicked';
"""
)
except PageDisconnectedError:
refresh_active_page()
if has_profile_form():
print("[*] 确认邮箱后页面跳转成功,已进入最终注册页。")
return code
clicked = 'disconnected'
if clicked == 'clicked':
print(f"[*] 已填写验证码并点击确认邮箱: {code}")
time.sleep(2)
refresh_active_page()
if has_profile_form():
print("[*] 验证码确认完成,最终注册页已就绪。")
return code
if clicked == 'no-button':
current_url = page.url
if 'sign-up' in current_url or 'signup' in current_url:
print(f"[*] 已填写验证码,页面已自动跳转到下一步: {current_url}")
return code
if clicked == 'disconnected':
time.sleep(1)
continue
time.sleep(0.5)
debug_snapshot = page.run_js(
r"""
function isVisible(node) {
if (!node) {
return false;
}
const style = window.getComputedStyle(node);
if (style.display === 'none' || style.visibility === 'hidden' || style.opacity === '0') {
return false;
}
const rect = node.getBoundingClientRect();
return rect.width > 0 && rect.height > 0;
}
const inputs = Array.from(document.querySelectorAll('input')).filter(isVisible).map((node) => ({
type: node.type || '',
name: node.name || '',
testid: node.getAttribute('data-testid') || '',
autocomplete: node.autocomplete || '',
maxLength: Number(node.maxLength || 0),
value: String(node.value || ''),
}));
const buttons = Array.from(document.querySelectorAll('button')).filter(isVisible).map((node) => ({
text: String(node.innerText || node.textContent || '').replace(/\s+/g, ' ').trim(),
disabled: !!node.disabled,
ariaDisabled: node.getAttribute('aria-disabled') || '',
}));
return { url: location.href, inputs, buttons };
"""
)
print(f"[Debug] 验证码页 DOM 摘要: {debug_snapshot}")
raise Exception("未找到验证码输入框或确认邮箱按钮")
def getTurnstileToken():
# 复用现有 turnstile 处理逻辑,在最终注册页需要时再触发。
page.run_js("try { turnstile.reset() } catch(e) { }")
turnstileResponse = None
for i in range(0, 15):
try:
turnstileResponse = page.run_js("try { return turnstile.getResponse() } catch(e) { return null }")
if turnstileResponse:
return turnstileResponse
challengeSolution = page.ele("@name=cf-turnstile-response")
challengeWrapper = challengeSolution.parent()
challengeIframe = challengeWrapper.shadow_root.ele("tag:iframe")
challengeIframe.run_js("""
window.dtp = 1
function getRandomInt(min, max) {
return Math.floor(Math.random() * (max - min + 1)) + min;
}
// 旧方案在 4K 屏下不稳定,这里给出更自然的屏幕坐标。
let screenX = getRandomInt(800, 1200);
let screenY = getRandomInt(400, 600);
Object.defineProperty(MouseEvent.prototype, 'screenX', { value: screenX });
Object.defineProperty(MouseEvent.prototype, 'screenY', { value: screenY });
""")
challengeIframeBody = challengeIframe.ele("tag:body").shadow_root
challengeButton = challengeIframeBody.ele("tag:input")
challengeButton.click()
except:
pass
time.sleep(1)
raise Exception("failed to solve turnstile")
def build_profile():
# 生成一组可重复使用的注册资料,密码至少包含大小写、数字和特殊字符。
given_name = "Neo"
family_name = "Lin"
password = "N" + secrets.token_hex(4) + "!a7#" + secrets.token_urlsafe(6)
return given_name, family_name, password
def fill_profile_and_submit(timeout=30):
# 在验证码通过后,直接锁定“可见且可写”的真实输入框,避免命中隐藏节点或 React 受控副本。
given_name, family_name, password = build_profile()
deadline = time.time() + timeout
turnstile_token = ""
while time.time() < deadline:
filled = page.run_js(
"""
const givenName = arguments[0];
const familyName = arguments[1];
const password = arguments[2];
function isVisible(node) {
if (!node) {
return false;
}
const style = window.getComputedStyle(node);
if (style.display === 'none' || style.visibility === 'hidden' || style.opacity === '0') {
return false;
}
const rect = node.getBoundingClientRect();
return rect.width > 0 && rect.height > 0;
}
function pickInput(selector) {
return Array.from(document.querySelectorAll(selector)).find((node) => {
return isVisible(node) && !node.disabled && !node.readOnly;
}) || null;
}
function setInputValue(input, value) {
if (!input) {
return false;
}
input.focus();
input.click();
const nativeSetter = Object.getOwnPropertyDescriptor(window.HTMLInputElement.prototype, 'value')?.set;
const tracker = input._valueTracker;
if (tracker) {
tracker.setValue('');
}
if (nativeSetter) {
nativeSetter.call(input, '');
nativeSetter.call(input, value);
} else {
input.value = '';
input.value = value;
}
input.dispatchEvent(new InputEvent('beforeinput', {
bubbles: true,
cancelable: true,
data: value,
inputType: 'insertText',
}));
input.dispatchEvent(new InputEvent('input', {
bubbles: true,
cancelable: true,
data: value,
inputType: 'insertText',
}));
input.dispatchEvent(new Event('change', { bubbles: true }));
input.dispatchEvent(new Event('blur', { bubbles: true }));
return String(input.value || '') === String(value || '');
}
const givenInput = pickInput('input[data-testid="givenName"], input[name="givenName"], input[autocomplete="given-name"]');
const familyInput = pickInput('input[data-testid="familyName"], input[name="familyName"], input[autocomplete="family-name"]');
const passwordInput = pickInput('input[data-testid="password"], input[name="password"], input[type="password"]');
if (!givenInput || !familyInput || !passwordInput) {
return 'not-ready';
}
const givenOk = setInputValue(givenInput, givenName);
const familyOk = setInputValue(familyInput, familyName);
const passwordOk = setInputValue(passwordInput, password);
if (!givenOk || !familyOk || !passwordOk) {
return 'filled-failed';
}
return [
String(givenInput.value || '').trim() === String(givenName || '').trim(),
String(familyInput.value || '').trim() === String(familyName || '').trim(),
String(passwordInput.value || '') === String(password || ''),
].every(Boolean) ? 'filled' : 'verify-failed';
""",
given_name,
family_name,
password,
)
if filled == 'not-ready':
time.sleep(0.5)
continue
if filled != 'filled':
print(f"[Debug] 最终注册页输入框已出现,但姓名/密码写入失败: {filled}")
time.sleep(0.5)
continue
values_ok = page.run_js(
"""
const expectedGiven = arguments[0];
const expectedFamily = arguments[1];
const expectedPassword = arguments[2];
function isVisible(node) {
if (!node) {
return false;
}
const style = window.getComputedStyle(node);
if (style.display === 'none' || style.visibility === 'hidden' || style.opacity === '0') {
return false;
}
const rect = node.getBoundingClientRect();
return rect.width > 0 && rect.height > 0;
}
function pickInput(selector) {
return Array.from(document.querySelectorAll(selector)).find((node) => {
return isVisible(node) && !node.disabled && !node.readOnly;
}) || null;
}
const givenInput = pickInput('input[data-testid="givenName"], input[name="givenName"], input[autocomplete="given-name"]');
const familyInput = pickInput('input[data-testid="familyName"], input[name="familyName"], input[autocomplete="family-name"]');
const passwordInput = pickInput('input[data-testid="password"], input[name="password"], input[type="password"]');
if (!givenInput || !familyInput || !passwordInput) {
return false;
}
return String(givenInput.value || '').trim() === String(expectedGiven || '').trim()
&& String(familyInput.value || '').trim() === String(expectedFamily || '').trim()
&& String(passwordInput.value || '') === String(expectedPassword || '');
""",
given_name,
family_name,
password,
)
if not values_ok:
print("[Debug] 最终注册页字段值校验失败,继续重试填写。")
time.sleep(0.5)
continue
turnstile_state = page.run_js(
"""
const challengeInput = document.querySelector('input[name="cf-turnstile-response"]');
if (!challengeInput) {
return 'not-found';
}
const value = String(challengeInput.value || '').trim();
return value ? 'ready' : 'pending';
"""
)
if turnstile_state == "pending" and not turnstile_token:
print("[*] 检测到最终注册页存在 Turnstile,开始使用现有真人化点击逻辑。")
turnstile_token = getTurnstileToken()
if turnstile_token:
synced = page.run_js(
"""
const token = arguments[0];
const challengeInput = document.querySelector('input[name="cf-turnstile-response"]');
if (!challengeInput) {
return false;
}
const nativeSetter = Object.getOwnPropertyDescriptor(window.HTMLInputElement.prototype, 'value')?.set;
if (nativeSetter) {
nativeSetter.call(challengeInput, token);
} else {
challengeInput.value = token;
}
challengeInput.dispatchEvent(new Event('input', { bubbles: true }));
challengeInput.dispatchEvent(new Event('change', { bubbles: true }));
return String(challengeInput.value || '').trim() === String(token || '').trim();
""",
turnstile_token,
)
if synced:
print("[*] Turnstile 响应已同步到最终注册表单。")
time.sleep(1.2)
try:
submit_button = page.ele('tag:button@@text()=完成注册') or page.ele('tag:button@@text():Create Account') or page.ele('tag:button@@text():Sign up')
except Exception:
submit_button = None
if not submit_button:
clicked = page.run_js(
r"""
const challengeInput = document.querySelector('input[name="cf-turnstile-response"]');
if (challengeInput && !String(challengeInput.value || '').trim()) {
return false;
}
const buttons = Array.from(document.querySelectorAll('button[type="submit"], button'));
const submitButton = buttons.find((node) => {
const text = (node.innerText || node.textContent || '').replace(/\s+/g, '');
const t = text.toLowerCase(); return text === '完成注册' || text.includes('完成注册') || t.includes('create account') || t.includes('sign up') || t.includes('complete');
});
if (!submitButton || submitButton.disabled || submitButton.getAttribute('aria-disabled') === 'true') {
return false;
}
submitButton.focus();
submitButton.click();
return true;
"""
)
else:
challenge_value = page.run_js(
"""
const challengeInput = document.querySelector('input[name="cf-turnstile-response"]');
return challengeInput ? String(challengeInput.value || '').trim() : 'not-found';
"""
)
if challenge_value not in ('not-found', ''):
submit_button.click()
clicked = True
else:
clicked = False
if clicked:
print(f"[*] 已填写注册资料并点击完成注册: {given_name} {family_name} / {password}")
return {
"given_name": given_name,
"family_name": family_name,
"password": password,
}
time.sleep(0.5)
raise Exception("未找到最终注册表单或完成注册按钮")
def extract_visible_numbers(timeout=60):
# 登录/注册完成后,提取页面上可见的普通数字文本,不处理任何敏感 Cookie。
deadline = time.time() + timeout
while time.time() < deadline:
result = page.run_js(
r"""
function isVisible(el) {
if (!el) {
return false;
}
const style = window.getComputedStyle(el);
if (style.display === 'none' || style.visibility === 'hidden' || style.opacity === '0') {
return false;
}
const rect = el.getBoundingClientRect();
return rect.width > 0 && rect.height > 0;
}
const selector = [
'h1', 'h2', 'h3', 'h4', 'h5', 'h6',
'div', 'span', 'p', 'strong', 'b', 'small',
'[data-testid]', '[class]', '[role="heading"]'
].join(',');
const seen = new Set();
const matches = [];
for (const node of document.querySelectorAll(selector)) {
if (!isVisible(node)) {
continue;
}
const text = String(node.innerText || node.textContent || '').replace(/\s+/g, ' ').trim();
if (!text) {
continue;
}
const found = text.match(/\d+(?:\.\d+)?/g);
if (!found) {
continue;
}
for (const value of found) {
const key = `${value}@@${text}`;
if (seen.has(key)) {
continue;
}
seen.add(key);
matches.push({ value, text });
}
}
return matches.slice(0, 30);
"""
)
if result:
print("[*] 页面可见数字文本提取结果:")
for item in result: