-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathselenium_cli.py
More file actions
2552 lines (2400 loc) · 112 KB
/
Copy pathselenium_cli.py
File metadata and controls
2552 lines (2400 loc) · 112 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 selenium import webdriver
from selenium.webdriver.firefox.options import Options as FirefoxOptions
from selenium.common.exceptions import (
WebDriverException, TimeoutException, NoSuchElementException,
NoSuchWindowException, StaleElementReferenceException
)
from selenium.webdriver.common.by import By
import time
import json
import os
import re
import hashlib
import mimetypes
import requests
from urllib.parse import urlparse, unquote, urljoin
from requests.adapters import HTTPAdapter
from urllib3.util.retry import Retry
from concurrent.futures import ThreadPoolExecutor, as_completed
import threading
DEFAULT_IMAGE_SUFFIXES = {
".jpg", ".jpeg", ".png", ".gif", ".bmp", ".webp",
".tif", ".tiff", ".heif", ".heic", ".svg", ".ico"
}
DEFAULT_FILE_SUFFIXES = {
".zip", ".rar", ".7z", ".tar", ".gz", ".bz2",
".pdf", ".doc", ".docx", ".xls", ".xlsx", ".ppt", ".pptx",
".txt", ".csv", ".json", ".xml", ".html", ".htm",
".mp3", ".wav", ".flac", ".aac", ".ogg",
".mp4", ".avi", ".mkv", ".mov", ".wmv", ".flv", ".webm",
".exe", ".msi", ".dmg", ".pkg", ".deb", ".rpm",
".apk", ".ipa",
".iso", ".img",
".epub", ".mobi", ".azw3"
}
LAZY_IMG_ATTRS = [
"data-src", "data-original", "data-lazy-src", "data-url",
"data-actualsrc", "data-echo", "data-defer", "data-img",
"data-background-image", "data-lazy", "data-placeholder"
]
class FirefoxAutoBrowser:
def __init__(self, command_executor='http://127.0.0.1:4444',
firefox_binary_path="C:\\Program Files\\Mozilla Firefox\\firefox.exe",
page_load_timeout=30, implicitly_wait=10,
download_max_workers=5):
"""
Initialize browser driver and configuration
:param command_executor: Remote driver address
:param firefox_binary_path: Firefox executable file path
:param page_load_timeout: Page load timeout time
:param implicitly_wait: Element implicit wait time
:param download_max_workers: 批量下载最大并发线程数,默认 5
"""
self.driver = None
self.command_executor = command_executor
self.firefox_binary_path = firefox_binary_path
self.page_load_timeout = page_load_timeout
self.implicitly_wait = implicitly_wait
self.download_max_workers = download_max_workers
self._print_lock = threading.Lock()
self.init_result = self._init_browser()
self._req_session = self._create_request_session()
def _create_request_session(self):
"""Create a requests session with automatic retries"""
session = requests.Session()
retry_strategy = Retry(
total=3,
backoff_factor=0.5,
status_forcelist=[429, 500, 502, 503, 504]
)
adapter = HTTPAdapter(max_retries=retry_strategy)
session.mount("http://", adapter)
session.mount("https://", adapter)
return session
def _log(self, msg):
with self._print_lock:
print(msg)
def _sync_browser_cookies(self):
if not self.driver:
return
try:
cookies = self.driver.get_cookies()
for ck in cookies:
self._req_session.cookies.set(
ck.get("name"), ck.get("value"),
domain=ck.get("domain"), path=ck.get("path")
)
except Exception:
pass
def _build_headers(self, referer=None, extra_headers=None):
headers = {
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:121.0) Gecko/20100101 Firefox/121.0",
"Accept": "*/*",
"Accept-Language": "zh-CN,zh;q=0.9,en;q=0.8",
"Connection": "keep-alive"
}
if referer:
headers["Referer"] = referer
if extra_headers and isinstance(extra_headers, dict):
headers.update(extra_headers)
return headers
@staticmethod
def _resolve_url(url, base_url):
"""
将相对 URL 转为绝对 URL。
:param url: 可能是相对路径的 URL
:param base_url: 当前页面地址,作为拼接基准
:return: 绝对 URL;若无法解析则返回原 url
"""
if not url or not base_url:
return url
url = url.strip()
if url.startswith(("http://", "https://", "//")):
if url.startswith("//"):
return "https:" + url
return url
if url.startswith("data:") or url.startswith("blob:"):
return url
try:
return urljoin(base_url, url)
except Exception:
return url
@staticmethod
def _sanitize_filename(name):
"""
清理文件名中的非法字符,兼容 Windows / Linux / macOS。
"""
if not name:
return "unnamed"
# 替换路径分隔符和控制字符
name = re.sub(r'[\\/:*?"<>|\r\n\t]+', "_", name)
# 去除首尾空格和点
name = name.strip(" .")
# 限制长度
if len(name) > 200:
root, ext = os.path.splitext(name)
name = root[:190] + ext
return name if name else "unnamed"
@staticmethod
def _extract_filename_from_disposition(resp, fallback="download_file"):
"""
从 HTTP 响应头 Content-Disposition 中提取文件名。
支持 filename= 和 filename*= 两种写法。
:return: 提取到的文件名(不含路径),提取失败返回 fallback
"""
cd = resp.headers.get("Content-Disposition", "")
if not cd:
return fallback
# 优先 filename*=UTF-8''xxx
m = re.search(r"filename\*\s*=\s*([^;]+)", cd, re.IGNORECASE)
if m:
raw = m.group(1).strip().strip('"').strip("'")
# 处理 UTF-8''编码
if "''" in raw:
raw = raw.split("''", 1)[1]
try:
return unquote(raw)
except Exception:
return raw
# 其次 filename=xxx
m = re.search(r'filename\s*=\s*"?([^";]+)"?', cd, re.IGNORECASE)
if m:
return m.group(1).strip()
return fallback
@staticmethod
def _guess_extension_from_content_type(resp, fallback=""):
"""根据响应 Content-Type 猜测文件扩展名"""
ct = resp.headers.get("Content-Type", "").split(";")[0].strip().lower()
if not ct:
return fallback
ext = mimetypes.guess_extension(ct)
if ext:
# mimetypes 对 jpeg 返回 .jpe,修正一下
if ext == ".jpe":
ext = ".jpg"
return ext
# 常见映射补充
ct_map = {
"image/jpeg": ".jpg", "image/jpg": ".jpg",
"image/png": ".png", "image/gif": ".gif",
"image/webp": ".webp", "image/bmp": ".jpg",
"image/svg+xml": ".svg",
"application/pdf": ".pdf",
"application/zip": ".zip",
"application/x-rar-compressed": ".rar",
"application/x-7z-compressed": ".7z",
"application/gzip": ".gz",
"application/x-tar": ".tar",
"application/msword": ".doc",
"application/vnd.openxmlformats-officedocument.wordprocessingml.document": ".docx",
"application/vnd.ms-excel": ".xls",
"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet": ".xlsx",
"text/plain": ".txt", "text/csv": ".csv",
"application/json": ".json",
"video/mp4": ".mp4", "video/x-matroska": ".mkv",
"audio/mpeg": ".mp3", "audio/wav": ".wav",
}
return ct_map.get(ct, fallback)
def _ensure_dir(self, save_dir):
"""确保目录存在,失败抛出异常"""
try:
if not os.path.exists(save_dir):
os.makedirs(save_dir, exist_ok=True)
except PermissionError:
raise Exception(f"No permission to create directory {save_dir}")
def _get_unique_save_path(self, save_dir, filename):
"""
若目标文件已存在,自动追加 _1, _2 ... 避免覆盖。
返回最终唯一路径。
"""
base, ext = os.path.splitext(filename)
candidate = os.path.join(save_dir, filename)
counter = 1
while os.path.exists(candidate):
candidate = os.path.join(save_dir, f"{base}_{counter}{ext}")
counter += 1
return candidate
def _stream_download(self, url, save_path, headers=None, timeout=30,
show_progress=False, resume=False, chunk_size=8192):
"""
通用流式下载核心方法。
:param url: 下载地址
:param save_path: 保存完整路径
:param headers: 请求头
:param timeout: 超时秒数
:param show_progress: 是否打印进度
:param resume: 是否启用断点续传(若文件已存在且服务器支持 Range)
:param chunk_size: 块大小
:return: (total_size_bytes, used_headers_dict)
"""
existing_size = 0
mode = "wb"
if resume and os.path.exists(save_path):
existing_size = os.path.getsize(save_path)
if existing_size > 0:
headers = dict(headers or {})
headers["Range"] = f"bytes={existing_size}-"
mode = "ab"
resp = self._req_session.get(url, headers=headers, timeout=timeout, stream=True)
# 206 表示断点续传成功;200 表示服务器不支持 Range,从头开始
if resp.status_code == 200 and existing_size > 0:
mode = "wb"
existing_size = 0
resp.raise_for_status()
total_size = existing_size
content_length = resp.headers.get("Content-Length")
total_expected = None
if content_length and content_length.isdigit():
total_expected = int(content_length) + existing_size
try:
with open(save_path, mode) as f:
downloaded = existing_size
for chunk in resp.iter_content(chunk_size=chunk_size):
if chunk:
f.write(chunk)
downloaded += len(chunk)
total_size = downloaded
if show_progress and total_expected:
pct = min(100.0, downloaded * 100.0 / total_expected)
self._log(f" 下载进度: {downloaded}/{total_expected} bytes ({pct:.1f}%)")
except OSError as e:
raise Exception(f"Write file failed, disk full or permission denied: {str(e)}")
return total_size, dict(resp.headers)
def _scroll_page_to_load_lazy_images(self, scroll_step=800, wait_per_step=0.4, max_rounds=50):
"""
缓慢滚动整个页面,触发懒加载图片加载。
很多网站图片在滚动到可视区域时才把 data-src 赋给 src。
"""
if not self.driver:
return
try:
last_height = self.driver.execute_script("return document.body.scrollHeight")
for _ in range(max_rounds):
self.driver.execute_script(f"window.scrollBy(0, {scroll_step});")
time.sleep(wait_per_step)
new_height = self.driver.execute_script("return document.body.scrollHeight")
# 滚到底部且高度不再变化,结束
current_scroll = self.driver.execute_script("return window.scrollY + window.innerHeight")
if current_scroll >= new_height - 10 and new_height == last_height:
break
last_height = new_height
# 滚回顶部
self.driver.execute_script("window.scrollTo(0, 0);")
time.sleep(0.3)
except Exception:
pass
def _init_browser(self):
"""
Private method: Configure Firefox options and initialize Remote driver
Return: JSON format initialization result
"""
try:
firefox_options = FirefoxOptions()
firefox_options.binary_location = self.firefox_binary_path
custom_user_agent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:121.0) Gecko/20100101 Firefox/121.0"
firefox_options.add_argument(f"--user-agent={custom_user_agent}")
firefox_options.set_preference("dom.webnotifications.enabled", False)
firefox_options.set_preference("dom.popup_maximum", -1)
firefox_options.set_preference("browser.popups.showPopupBlocker", False)
firefox_options.set_preference("dom.disable_open_during_load", False)
firefox_options.set_preference("browser.link.open_newwindow", 3)
firefox_options.set_preference("browser.link.open_newwindow.restriction", 0)
firefox_options.add_argument("--ignore-certificate-errors")
self.driver = webdriver.Remote(
command_executor=self.command_executor,
options=firefox_options
)
self.driver.set_page_load_timeout(self.page_load_timeout)
self.driver.implicitly_wait(self.implicitly_wait)
success_json = {
"code": 200,
"status": "success",
"message": "Browser initialized successfully",
"detail": None,
"data": None
}
return json.dumps(success_json, ensure_ascii=False, indent=2)
except (WebDriverException, Exception) as e:
fail_json = {
"code": 500,
"status": "failed",
"message": f"Browser initialization failed: {str(e)}",
"detail": None,
"data": None
}
return json.dumps(fail_json, ensure_ascii=False, indent=2)
def create_new_tab(self):
"""
Function: Create a new blank tab
Return: JSON format string (contains operation result and related information)
"""
try:
if not self.driver:
raise Exception("Browser driver not initialized")
self.driver.execute_script("window.open('');")
result_json = {
"code": 200,
"status": "success",
"message": "New tab created successfully",
"detail": None,
"data": None
}
return json.dumps(result_json, ensure_ascii=False, indent=2)
except (WebDriverException, Exception) as e:
fail_json = {
"code": 500,
"status": "failed",
"message": f"Failed to create new tab: {str(e)}",
"detail": None,
"data": None
}
return json.dumps(fail_json, ensure_ascii=False, indent=2)
def get_all_tabs(self):
"""
Function: Get the list of handles of all current tabs, including detailed tab information + page title
Return: JSON format string (contains detailed tab information and handle list data)
"""
try:
if not self.driver:
raise Exception("Browser driver not initialized")
window_handles = self.driver.window_handles
tab_count = len(window_handles)
original_active_handle = self.driver.current_window_handle
tabs_detail = {
"total_tabs": tab_count,
"tabs_info": []
}
for index, handle in enumerate(window_handles):
try:
self.driver.switch_to.window(handle)
page_title = self.driver.title.strip()
except (NoSuchWindowException, WebDriverException):
page_title = "[Tab window invalid, closed]"
active_handle = original_active_handle
tab_status = "[Currently Active]" if (active_handle and handle == active_handle) else "[Inactive]"
tab_info = {
"index": index,
"handle": handle,
"handle_abbr": handle[:20] + "...",
"title": page_title,
"status": tab_status
}
tabs_detail["tabs_info"].append(tab_info)
try:
self.driver.switch_to.window(original_active_handle)
except Exception:
pass
result_json = {
"code": 200,
"status": "success",
"message": f"Successfully retrieved {tab_count} tabs in total",
"detail": tabs_detail,
"data": window_handles
}
return json.dumps(result_json, ensure_ascii=False, indent=2)
except (WebDriverException, Exception) as e:
fail_json = {
"code": 500,
"status": "failed",
"message": f"Failed to get all tabs: {str(e)}",
"detail": None,
"data": None
}
return json.dumps(fail_json, ensure_ascii=False, indent=2)
def get_active_tab(self):
"""
Function: Get the handle of the currently active (foreground display) tab, including detailed active tab information
Return: JSON format string (contains active tab details and handle data)
"""
try:
if not self.driver:
raise Exception("Browser driver not initialized")
current_window = self.driver.current_window_handle
all_handles = self.driver.window_handles
tab_count = len(all_handles)
active_tab_index = all_handles.index(current_window)
active_detail = {
"total_tabs": tab_count,
"active_tab_index": active_tab_index,
"active_tab_handle": current_window
}
result_json = {
"code": 200,
"status": "success",
"message": "Successfully retrieved current active tab information",
"detail": active_detail,
"data": current_window
}
return json.dumps(result_json, ensure_ascii=False, indent=2)
except (WebDriverException, Exception) as e:
fail_json = {
"code": 500,
"status": "failed",
"message": f"Failed to get active tab: {str(e)}",
"detail": None,
"data": None
}
return json.dumps(fail_json, ensure_ascii=False, indent=2)
def switch_to_specific_tab(self, target):
"""
Function: Switch to a specific tab (supports passing handle directly / passing tab index)
:param target: Target tab (str: tab handle; int: tab index, starting from 0)
Return: JSON format string (contains switch result and related information)
"""
try:
if not self.driver:
raise Exception("Browser driver not initialized")
all_handles = self.driver.window_handles
target_handle = None
if isinstance(target, int):
if 0 <= target < len(all_handles):
target_handle = all_handles[target]
else:
raise Exception(
f"Tab index {target} is invalid, only {len(all_handles)} tabs exist currently (index 0~{len(all_handles) - 1})")
elif isinstance(target, str):
if target in all_handles:
target_handle = target
else:
raise Exception(f"Tab handle {target} is invalid, not in the current tab list")
else:
raise Exception("Invalid parameter type, supports int (index) or str (handle)")
self.driver.switch_to.window(target_handle)
result_json = {
"code": 200,
"status": "success",
"message": "Successfully switched to target tab",
"detail": {
"target_param": target,
"target_handle": target_handle,
"target_handle_abbr": target_handle[:20] + "..."
},
"data": None
}
return json.dumps(result_json, ensure_ascii=False, indent=2)
except (WebDriverException, Exception) as e:
fail_json = {
"code": 500,
"status": "failed",
"message": f"Failed to switch to specific tab: {str(e)}",
"detail": {
"input_target": target
},
"data": None
}
return json.dumps(fail_json, ensure_ascii=False, indent=2)
def open_url_in_specific_tab(self, url, target=0):
"""
Function: Open the specified web page in a specific tab
:param url: Web page address to open (str)
:param target: Target tab (str: handle; int: index, default the first tab (index 0))
Return: JSON format string (contains operation result and related information)
"""
try:
if not self.driver:
raise Exception("Browser driver not initialized")
if not url or not isinstance(url, str) or url.strip() == "":
raise Exception("Invalid web page address, empty url")
switch_result = json.loads(self.switch_to_specific_tab(target))
if switch_result["code"] != 200:
raise Exception(switch_result["message"])
self.driver.get(url.strip())
time.sleep(0.8)
result_json = {
"code": 200,
"status": "success",
"message": f"Successfully opened web page in target tab: {url}",
"detail": {
"target_tab": target,
"opened_url": url
},
"data": None
}
return json.dumps(result_json, ensure_ascii=False, indent=2)
except (TimeoutException, WebDriverException) as e:
fail_json = {
"code": 500,
"status": "failed",
"message": f"Web page loading timed out or failed to open: {str(e)}",
"detail": {
"target_tab": target,
"input_url": url
},
"data": None
}
return json.dumps(fail_json, ensure_ascii=False, indent=2)
except (Exception) as e:
fail_json = {
"code": 500,
"status": "failed",
"message": f"Failed to open web page in specific tab: {str(e)}",
"detail": {
"target_tab": target,
"input_url": url
},
"data": None
}
return json.dumps(fail_json, ensure_ascii=False, indent=2)
def get_specific_tab_page_content(self, target=None):
"""
Function: Get the page HTML content of the specified tab (default to get current active tab)
:param target: Target tab (None: current active tab; str: handle; int: index)
Return: JSON format string (contains page content length and HTML source data)
"""
try:
if not self.driver:
raise Exception("Browser driver not initialized")
current_handle = None
target_info = {}
if target is None:
current_handle = self.driver.current_window_handle
target_info = {
"target_type": "current_active",
"target_handle": current_handle,
"target_handle_abbr": current_handle[:20] + "..."
}
else:
all_handles = self.driver.window_handles
target_handle = None
if isinstance(target, int):
if 0 <= target < len(all_handles):
target_handle = all_handles[target]
target_info = {
"target_type": "index",
"input_target": target,
"target_handle": target_handle,
"target_handle_abbr": target_handle[:20] + "..."
}
else:
raise Exception(f"Tab index {target} is invalid, only {len(all_handles)} tabs exist currently")
elif isinstance(target, str):
if target in all_handles:
target_handle = target
target_info = {
"target_type": "handle",
"input_target": target,
"target_handle": target_handle,
"target_handle_abbr": target_handle[:20] + "..."
}
else:
raise Exception(f"Tab handle {target} is invalid, not in the current tab list")
else:
raise Exception("Invalid parameter type, supports int (index) or str (handle)")
self.driver.switch_to.window(target_handle)
current_handle = target_handle
page_content = self.driver.page_source
content_length = len(page_content)
target_info["content_length"] = content_length
result_json = {
"code": 200,
"status": "success",
"message": f"Successfully retrieved target tab page content, content length: {content_length} characters",
"detail": target_info,
"data": page_content
}
return json.dumps(result_json, ensure_ascii=False, indent=2)
except WebDriverException as e:
fail_json = {
"code": 500,
"status": "failed",
"message": f"Failed to get tab page content (WebDriver exception): {str(e)}",
"detail": {
"input_target": target
},
"data": None
}
return json.dumps(fail_json, ensure_ascii=False, indent=2)
except Exception as e:
fail_json = {
"code": 500,
"status": "failed",
"message": f"Failed to get tab page content: {str(e)}",
"detail": {
"input_target": target
},
"data": None
}
return json.dumps(fail_json, ensure_ascii=False, indent=2)
def scroll_mouse_wheel_down(self, scroll_distance=500, target_tab=None):
"""
Function: Simulate mouse wheel scrolling down (supports specifying tab, default current active tab)
:param scroll_distance: Scrolling distance (pixels, default 500 pixels, larger value means more scrolling)
:param target_tab: Target tab (None: current active tab; str: handle; int: index)
Return: JSON format string (contains scrolling operation result)
"""
try:
if not self.driver:
raise Exception("Browser driver not initialized")
scroll_detail = {
"scroll_direction": "down",
"scroll_distance": scroll_distance,
"target_tab": target_tab
}
if target_tab is not None:
switch_result = json.loads(self.switch_to_specific_tab(target_tab))
if switch_result["code"] != 200:
raise Exception(switch_result["message"])
scroll_detail["switch_status"] = "Successfully switched to target tab"
self.driver.execute_script(f"window.scrollBy(0, {scroll_distance});")
result_json = {
"code": 200,
"status": "success",
"message": f"Mouse wheel scrolled down successfully, scrolling distance: {scroll_distance} pixels",
"detail": scroll_detail,
"data": None
}
return json.dumps(result_json, ensure_ascii=False, indent=2)
except WebDriverException as e:
fail_json = {
"code": 500,
"status": "failed",
"message": f"Failed to scroll mouse wheel down (WebDriver exception): {str(e)}",
"detail": {
"scroll_distance": scroll_distance,
"target_tab": target_tab
},
"data": None
}
return json.dumps(fail_json, ensure_ascii=False, indent=2)
except Exception as e:
fail_json = {
"code": 500,
"status": "failed",
"message": f"Failed to scroll mouse wheel down: {str(e)}",
"detail": {
"scroll_distance": scroll_distance,
"target_tab": target_tab
},
"data": None
}
return json.dumps(fail_json, ensure_ascii=False, indent=2)
def scroll_mouse_wheel_up(self, scroll_distance=500, target_tab=None):
"""
Function: Simulate mouse wheel scrolling up (supports specifying tab, default current active tab)
:param scroll_distance: Scrolling distance (pixels, default 500 pixels, larger value means more scrolling)
:param target_tab: Target tab (None: current active tab; str: handle; int: index)
Return: JSON format string (contains scrolling operation result)
"""
try:
if not self.driver:
raise Exception("Browser driver not initialized")
scroll_detail = {
"scroll_direction": "up",
"scroll_distance": scroll_distance,
"target_tab": target_tab
}
if target_tab is not None:
switch_result = json.loads(self.switch_to_specific_tab(target_tab))
if switch_result["code"] != 200:
raise Exception(switch_result["message"])
scroll_detail["switch_status"] = "Successfully switched to target tab"
self.driver.execute_script(f"window.scrollBy(0, -{scroll_distance});")
result_json = {
"code": 200,
"status": "success",
"message": f"Mouse wheel scrolled up successfully, scrolling distance: {scroll_distance} pixels",
"detail": scroll_detail,
"data": None
}
return json.dumps(result_json, ensure_ascii=False, indent=2)
except WebDriverException as e:
fail_json = {
"code": 500,
"status": "failed",
"message": f"Failed to scroll mouse wheel up (WebDriver exception): {str(e)}",
"detail": {
"scroll_distance": scroll_distance,
"target_tab": target_tab
},
"data": None
}
return json.dumps(fail_json, ensure_ascii=False, indent=2)
except Exception as e:
fail_json = {
"code": 500,
"status": "failed",
"message": f"Failed to scroll mouse wheel up: {str(e)}",
"detail": {
"scroll_distance": scroll_distance,
"target_tab": target_tab
},
"data": None
}
return json.dumps(fail_json, ensure_ascii=False, indent=2)
def click_element_by_xpath(self, xpath, target_tab=None):
"""
Function: Locate element by XPath expression and execute click operation
:param xpath: XPath expression for targeting the element (str, required)
:param target_tab: Target tab (None: current active tab; str: handle; int: index)
Return: JSON format string (contains element locate and click operation result)
"""
try:
if not self.driver:
raise Exception("Browser driver not initialized")
if not xpath or not isinstance(xpath, str):
raise Exception("Invalid XPath expression: it must be a non-empty string")
click_detail = {
"xpath_expression": xpath,
"target_tab": target_tab,
"operation_status": "not_executed"
}
if target_tab is not None:
switch_result = json.loads(self.switch_to_specific_tab(target_tab))
if switch_result["code"] != 200:
raise Exception(f"Failed to switch to target tab: {switch_result['message']}")
click_detail["switch_status"] = "Successfully switched to target tab"
click_detail["operation_status"] = "locating_element"
target_element = self.driver.find_element(By.XPATH, xpath)
if not target_element:
raise NoSuchElementException("Element not found even with valid XPath expression")
click_detail["operation_status"] = "clicking_element"
target_element.click()
click_detail["operation_status"] = "completed_successfully"
result_json = {
"code": 200,
"status": "success",
"message": "Element located by XPath and clicked successfully",
"detail": click_detail,
"data": None
}
return json.dumps(result_json, ensure_ascii=False, indent=2)
except NoSuchElementException as e:
fail_json = {
"code": 404,
"status": "failed",
"message": f"Element not found by XPath: {str(e)}",
"detail": {
"xpath_expression": xpath,
"target_tab": target_tab,
"error_type": "NoSuchElementException"
},
"data": None
}
return json.dumps(fail_json, ensure_ascii=False, indent=2)
except StaleElementReferenceException as e:
fail_json = {
"code": 500,
"status": "failed",
"message": f"Element stale, page refreshed: {str(e)}",
"detail": {
"xpath_expression": xpath,
"target_tab": target_tab,
"error_type": "StaleElementReferenceException"
},
"data": None
}
return json.dumps(fail_json, ensure_ascii=False, indent=2)
except WebDriverException as e:
fail_json = {
"code": 500,
"status": "failed",
"message": f"Failed to click element (WebDriver exception): {str(e)}",
"detail": {
"xpath_expression": xpath,
"target_tab": target_tab,
"error_type": "WebDriverException"
},
"data": None
}
return json.dumps(fail_json, ensure_ascii=False, indent=2)
except Exception as e:
fail_json = {
"code": 500,
"status": "failed",
"message": f"Failed to click element by XPath: {str(e)}",
"detail": {
"xpath_expression": xpath,
"target_tab": target_tab,
"error_type": "GeneralException"
},
"data": None
}
return json.dumps(fail_json, ensure_ascii=False, indent=2)
def click_element(self, locator, locator_type="xpath", target_tab=None):
"""
Function: Universal element click function, supports multiple locator methods to click any clickable element
(tags, buttons, links, etc.)
:param locator: Locator expression (str, required, e.g. id value, XPath expression, CSS selector, etc.)
:param locator_type: Locator method (str, optional, default "xpath"), support:
"id", "xpath", "name", "class_name", "css_selector", "tag_name", "link_text", "partial_link_text"
:param target_tab: Target tab (None: current active tab; str: handle; int: index)
Return: JSON format string (contains element locate and click operation result)
"""
supported_locators = {
"id": By.ID,
"xpath": By.XPATH,
"name": By.NAME,
"class_name": By.CLASS_NAME,
"css_selector": By.CSS_SELECTOR,
"tag_name": By.TAG_NAME,
"link_text": By.LINK_TEXT,
"partial_link_text": By.PARTIAL_LINK_TEXT
}
try:
if not self.driver:
raise Exception("Browser driver not initialized")
if locator_type not in supported_locators:
supported_types = ", ".join(supported_locators.keys())
raise Exception(f"Unsupported locator type: {locator_type}. Supported types: {supported_types}")
if not locator or not isinstance(locator, str):
raise Exception("Invalid locator expression: it must be a non-empty string")
click_detail = {
"locator_type": locator_type,
"locator_expression": locator,
"target_tab": target_tab,
"operation_status": "not_executed"
}
if target_tab is not None:
switch_result = json.loads(self.switch_to_specific_tab(target_tab))
if switch_result["code"] != 200:
raise Exception(f"Failed to switch to target tab: {switch_result['message']}")
click_detail["switch_status"] = "Successfully switched to target tab"
click_detail["operation_status"] = "locating_element"
by_locator = supported_locators[locator_type]
target_element = self.driver.find_element(by_locator, locator)
if not target_element:
raise NoSuchElementException(f"Element not found even with valid {locator_type} locator")
click_detail["operation_status"] = "scrolling_to_element"
self.driver.execute_script("arguments[0].scrollIntoView({behavior: 'smooth', block: 'center'});", target_element)
click_detail["operation_status"] = "clicking_element"
target_element.click()
click_detail["operation_status"] = "completed_successfully"
result_json = {
"code": 200,
"status": "success",
"message": f"Element located by {locator_type} and clicked successfully",
"detail": click_detail,
"data": None
}
return json.dumps(result_json, ensure_ascii=False, indent=2)
except NoSuchElementException as e:
fail_json = {
"code": 404,
"status": "failed",
"message": f"Element not found by {locator_type}: {str(e)}",
"detail": {
"locator_type": locator_type,
"locator_expression": locator,
"target_tab": target_tab,
"error_type": "NoSuchElementException"
},
"data": None
}
return json.dumps(fail_json, ensure_ascii=False, indent=2)
except StaleElementReferenceException as e:
fail_json = {
"code": 500,
"status": "failed",
"message": f"Element stale reference: {str(e)}",
"detail": {
"locator_type": locator_type,
"locator_expression": locator,
"target_tab": target_tab,
"error_type": "StaleElementReferenceException"
},
"data": None
}
return json.dumps(fail_json, ensure_ascii=False, indent=2)
except WebDriverException as e:
fail_json = {
"code": 500,
"status": "failed",
"message": f"Failed to click element (WebDriver exception): {str(e)}",
"detail": {
"locator_type": locator_type,
"locator_expression": locator,
"target_tab": target_tab,
"error_type": "WebDriverException"
},
"data": None
}
return json.dumps(fail_json, ensure_ascii=False, indent=2)
except Exception as e:
fail_json = {
"code": 500,
"status": "failed",
"message": f"Failed to click element by {locator_type}: {str(e)}",
"detail": {
"locator_type": locator_type,
"locator_expression": locator,
"target_tab": target_tab,
"error_type": "GeneralException"
},
"data": None
}
return json.dumps(fail_json, ensure_ascii=False, indent=2)
def close_specific_tab(self, target=None):
"""
Function: Close a specific tab (default to close current active tab, supports specifying handle/index)
:param target: Target tab (None: current active tab; str: handle; int: index)
Return: JSON format string (contains close operation result and subsequent switch information)
"""
try:
if not self.driver:
raise Exception("Browser driver not initialized")
all_handles = self.driver.window_handles
tab_count_before_close = len(all_handles)
if tab_count_before_close == 0:
raise Exception("No available tabs to close currently")
close_handle = None
close_detail = {
"tab_count_before_close": tab_count_before_close,
"input_target": target
}
if target is None:
close_handle = self.driver.current_window_handle
close_detail["target_type"] = "current_active"
else:
if isinstance(target, int):
if 0 <= target < tab_count_before_close:
close_handle = all_handles[target]
close_detail["target_type"] = "index"
else:
raise Exception(f"Tab index {target} is invalid, only {tab_count_before_close} tabs exist currently")
elif isinstance(target, str):
if target in all_handles:
close_handle = target
close_detail["target_type"] = "handle"
else:
raise Exception(f"Tab handle {target} is invalid, not in the current tab list")
else:
raise Exception("Invalid parameter type, supports int (index) or str (handle)")
close_detail["closed_handle"] = close_handle
close_detail["closed_handle_abbr"] = close_handle[:20] + "..."
self.driver.switch_to.window(close_handle)
is_last_tab = (tab_count_before_close == 1)
close_detail["is_last_tab"] = is_last_tab
self.driver.close()
if not is_last_tab: