forked from NaiboWang/EasySpider
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.js
1642 lines (1600 loc) · 71.4 KB
/
main.js
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
// Modules to control application life and create native browser window
const {
app,
BrowserWindow,
dialog,
ipcMain,
screen,
session,
} = require("electron");
app.commandLine.appendSwitch("--disable-http-cache");
const {
Builder,
By,
Key,
until,
Select,
StaleElementReferenceException,
} = require("selenium-webdriver");
const chrome = require("selenium-webdriver/chrome");
const {ServiceBuilder} = require("selenium-webdriver/chrome");
const {rootCertificates} = require("tls");
const {exit} = require("process");
const path = require("path");
const fs = require("fs");
const {exec, spawn, execFile} = require("child_process");
const iconPath = path.join(__dirname, "favicon.ico");
const task_server = require(path.join(__dirname, "server.js"));
const util = require("util");
let config = fs.readFileSync(
path.join(task_server.getDir(), `config.json`),
"utf8"
);
config = JSON.parse(config);
let config_context = JSON.parse(
fs.readFileSync(path.join(task_server.getDir(), `config.json`), "utf8")
); //仅在当前进程中使用,不会写入文件
if (config.debug) {
let logPath = "info.log";
let logFile = fs.createWriteStream(logPath, {flags: "a"});
console.log = function () {
logFile.write(util.format.apply(null, arguments) + "\n");
process.stdout.write(util.format.apply(null, arguments) + "\n");
};
console.error = function () {
logFile.write(util.format.apply(null, arguments) + "\n");
process.stderr.write(util.format.apply(null, arguments) + "\n");
};
}
let allWindowSockets = [];
let allWindowScoketNames = [];
if(config.webserver_address.includes("localhost") || config.webserver_address.includes("127.0.0.1")) {
task_server.start(config.webserver_port); //start local server
}
let server_address = `${config.webserver_address}:${config.webserver_port}`;
const websocket_port = 8084; //目前只支持8084端口,写死,因为扩展里面写死了
console.log("server_address: " + server_address);
let driverPath = "";
let chromeBinaryPath = "";
let execute_path = "";
console.log(process.arch);
// exec(`wmic os get Caption`, function (error, stdout, stderr) {
// if (error) {
// console.error(`执行的错误: ${error}`);
// return;
// }
// if (stdout.includes("Windows 7")) {
// console.log("Windows 7");
// let sys_arch = config.sys_arch;
// if (sys_arch === "x64") {
// dialog.showMessageBoxSync({
// type: "error",
// title: "Error",
// message:
// "Windows 7系统请下载使用x32版本的软件,不论Win 7系统为x64还是x32版本。\nFor Windows 7, please download and use the x32 version of the software, regardless of whether the Win 7 system is x64 or x32 version.",
// });
// }
// } else {
// console.log("Not Windows 7");
// }
// });
if (process.platform === "win32" && process.arch === "ia32") {
driverPath = path.join(__dirname, "chrome_win32/chromedriver_win32.exe");
chromeBinaryPath = path.join(__dirname, "chrome_win32/chrome.exe");
execute_path = path.join(__dirname, "chrome_win32/execute.bat");
} else if (process.platform === "win32" && process.arch === "x64") {
driverPath = path.join(__dirname, "chrome_win64/chromedriver_win64.exe");
chromeBinaryPath = path.join(__dirname, "chrome_win64/chrome.exe");
execute_path = path.join(__dirname, "chrome_win64/execute.bat");
} else if (process.platform === "darwin") {
driverPath = path.join(__dirname, "chromedriver_mac64");
chromeBinaryPath = path.join(
__dirname,
"chrome_mac64.app/Contents/MacOS/Google Chrome"
);
execute_path = path.join(__dirname, "");
} else if (process.platform === "linux") {
driverPath = path.join(__dirname, "chrome_linux64/chromedriver_linux64");
chromeBinaryPath = path.join(__dirname, "chrome_linux64/chrome");
execute_path = path.join(__dirname, "chrome_linux64/execute.sh");
}
console.log(driverPath, chromeBinaryPath, execute_path);
let language = "en";
let driver = null;
let mainWindow = null;
let flowchart_window = null;
let current_handle = null;
let old_handles = [];
let handle_pairs = {};
let socket_window = null;
let socket_start = null;
let socket_flowchart = null;
let invoke_window = null;
// var ffi = require('ffi-napi');
// var libm = ffi.Library('libm', {
// 'ceil': [ 'double', [ 'double' ] ]
// });
// libm.ceil(1.5); // 2
// const {user32FindWindowEx,
// winspoolGetDefaultPrinter,} = require('win32-api/fun');
// async function testt(){
// // 获取当前电脑当前用户默认打印机名
// const printerName = await winspoolGetDefaultPrinter()
// console.log(printerName);
// }
// testt();
function createWindow() {
// Create the browser window.
mainWindow = new BrowserWindow({
width: 600,
height: 800,
webPreferences: {
preload: path.join(__dirname, "src/js/preload.js"),
},
icon: iconPath,
// frame: false, //取消window自带的关闭最小化等
resizable: false, //禁止改变主窗口尺寸
});
// and load the index.html of the app.
// mainWindow.loadFile('src/index.html');
mainWindow.loadURL(
server_address +
"/index.html?user_data_folder=" +
config.user_data_folder +
"©right=" +
config.copyright,
{extraHeaders: "pragma: no-cache\n"}
);
// 隐藏菜单栏
const {Menu} = require("electron");
Menu.setApplicationMenu(null);
mainWindow.on("close", function (e) {
if (process.platform !== "darwin") {
app.quit();
}
});
// mainWindow.webContents.openDevTools();
// Open the DevTools.
// mainWindow.webContents.openDevTools()
}
async function findElementRecursive(driver, by, value, frames) {
for (const frame of frames) {
try {
// Try to switch to the frame
try {
await driver.switchTo().frame(frame);
} catch (error) {
if (error.name.indexOf("StaleElement") >= 0) {
// If the frame is stale, switch to the parent frame and then retry switching to the frame
await driver.switchTo().parentFrame();
await driver.switchTo().frame(frame);
} else {
// If it is another exception rethrow it
throw error;
}
}
let element;
try {
// Attempt to find the element in this frame
element = await driver.findElement(by(value));
return element;
} catch (error) {
if (error.name.indexOf("NoSuchElement") >= 0) {
// The element was not found in this frame, recurse into nested iframes
const nestedFrames = await driver.findElements(By.tagName("iframe"));
if (nestedFrames.length > 0) {
element = await findElementRecursive(
driver,
by,
value,
nestedFrames
);
if (element) {
return element;
}
}
} else {
// If it is another exception, log it
console.error(`Exception while processing frame: ${error}`);
}
}
} catch (error) {
console.error(`Exception while processing frame: ${error}`);
}
}
throw new Error(`Element ${value} not found in any frame or iframe`);
}
async function findElement(driver, by, value, iframe = false) {
// Switch back to the main document
await driver.switchTo().defaultContent();
if (iframe) {
const frames = await driver.findElements(By.tagName("iframe"));
if (frames.length === 0) {
throw new Error(
`No iframes found in the current page while searching for ${value}`
);
}
const element = await findElementRecursive(driver, by, value, frames);
return element;
} else {
// Find element in the main document as normal
let element = await driver.findElement(by(value));
return element;
}
}
async function findElementAcrossAllWindows(
msg,
notifyBrowser = true,
scrollIntoView = true
) {
let handles = await driver.getAllWindowHandles();
// console.log("handles", handles);
let content_handle = current_handle;
let id = -1;
try {
id = msg.message.id;
} catch {
id = msg.id;
}
if (id == -1) {
//如果是-1,从当前窗口开始搜索
content_handle = current_handle;
} else {
content_handle = handle_pairs[id];
}
// console.log(msg.message.id, content_handle);
let order = [
...handles.filter(
(handle) => handle != current_handle && handle != content_handle
),
current_handle,
content_handle,
]; //搜索顺序
let len = order.length;
let element = null;
let iframe = false;
try {
iframe = msg.message.iframe;
} catch {
iframe = msg.iframe;
}
// if (iframe) {
// notify_browser("在IFrame中执行操作可能需要较长时间,请耐心等待。", "Executing operations in IFrame may take a long time, please wait patiently.", "info");
// }
let xpath = "";
try {
xpath = msg.message.xpath;
} catch {
//如果msg.pathList存在,说明是循环中的元素
if (
msg.pathList != undefined &&
msg.pathList != null &&
msg.pathList != ""
) {
xpath = msg.pathList[0].trim();
} else {
xpath = msg.xpath;
}
}
if (xpath.indexOf("Field[") >= 0 || xpath.indexOf("eval(") >= 0) {
//两秒后通知浏览器
await new Promise((resolve) => setTimeout(resolve, 2000));
notify_browser(
'检测到XPath中包含Field[""]或eval(""),试运行时无法正常定位到包含此两项表达式的元素,请在任务正式运行阶段测试是否有效。',
'Field[""] or eval("") is detected in xpath, and the element containing these two expressions cannot be located normally during trial operation. Please test whether it is valid in the formal call stage.',
"warning"
);
return null;
}
let notify = false;
while (true) {
// console.log("handles");
try {
let h = order[len - 1];
console.log("current_handle", current_handle);
if (h != null && handles.includes(h)) {
await driver.switchTo().window(h);
current_handle = h;
console.log("switch to handle: ", h);
}
element = await findElement(driver, By.xpath, xpath, iframe);
break;
} catch (error) {
console.log("len", len);
len = len - 1;
if (!notify) {
notify = true;
// notify_browser("正在尝试在其他窗口中查找元素,请耐心等待。", "Trying to find elements in other windows, please wait patiently.", "info");
}
if (len == 0) {
break;
}
}
}
if (element == null && notifyBrowser) {
notify_browser(
"无法找到元素,请检查XPath是否正确:" + xpath,
"Cannot find the element, please check if the XPath is correct: " + xpath,
"warning"
);
}
if (element != null && scrollIntoView) {
// 浏览器切换到元素位置稍微靠上的位置
try {
// let script = `arguments[0].scrollIntoView(true);`;
let script = `arguments[0].scrollIntoView({block: "center", inline: "center"});`;
await driver.executeScript(script, element);
} catch (e) {
console.log("Cannot scrollIntoView");
}
}
return element;
}
async function beginInvoke(msg, ws) {
if (msg.type == 1) {
if (msg.message.id != -1) {
let url = "";
if (language == "zh") {
url =
server_address +
`/taskGrid/FlowChart_CN.html?id=${msg.message.id}&wsport=${websocket_port}&backEndAddressServiceWrapper=` +
server_address;
} else if (language == "en") {
url =
server_address +
`/taskGrid/FlowChart.html?id=${msg.message.id}&wsport=${websocket_port}&backEndAddressServiceWrapper=` +
server_address;
}
console.log(url);
flowchart_window.loadURL(url, {extraHeaders: "pragma: no-cache\n"});
}
mainWindow.hide();
// Prints the currently focused window bounds.
// This method has to be called on macOS before changing the window's bounds, otherwise it will throw an error.
// It will prompt an accessibility permission request dialog, if needed.
if (process.platform != "linux" && process.platform != "darwin") {
// 非用户信息模式下,设置窗口位置
if (
config_context.user_data_folder == null ||
config_context.user_data_folder == undefined ||
config_context.user_data_folder == ""
) {
const {windowManager} = require("node-window-manager");
const window = windowManager.getActiveWindow();
console.log(window);
windowManager.requestAccessibility();
// Sets the active window's bounds.
let size = screen.getPrimaryDisplay().workAreaSize;
let width = parseInt(size.width);
let height = parseInt(size.height * 0.6);
window.setBounds({
x: 0,
y: size.height * 0.4,
height: height,
width: width,
});
}
}
flowchart_window.show();
// flowchart_window.openDevTools();
} else if (msg.type == 2) {
// 键盘输入事件
// const robot = require("@jitsi/robotjs");
let keyInfo = msg.message.keyboardStr;
let enter = false;
if (/<enter>/i.test(keyInfo)) {
keyInfo = keyInfo.replace(/<enter>/gi, "");
enter = true;
}
let element = await findElementAcrossAllWindows(
msg,
(notifyBrowser = true),
(scrollIntoView = false)
);
await element.sendKeys(Key.HOME, Key.chord(Key.SHIFT, Key.END), keyInfo);
if (enter) {
await element.sendKeys(Key.ENTER);
}
} else if (msg.type == 3) {
try {
if (msg.from == 0) {
socket_flowchart.send(msg.message.pipe); //直接把消息转接
let message = JSON.parse(msg.message.pipe);
let type = message.type;
console.log("FROM Browser: ", message);
if (type.indexOf("Click") >= 0 || type.indexOf("Move") >= 0) {
let element = await findElementAcrossAllWindows(
message,
(notifyBrowser = true),
(scrollIntoView = false)
);
if (type.indexOf("Click") >= 0) {
await click_element(element, type);
} else if (type.indexOf("Move") >= 0) {
await driver.actions().move({origin: element}).perform();
}
}
} else {
send_message_to_browser(msg.message.pipe);
console.log("FROM Flowchart: ", JSON.parse(msg.message.pipe));
}
} catch (e) {
console.log(e);
}
} else if (msg.type == 4) {
//标记元素和试运行功能
let node = JSON.parse(msg.message.node);
let type = msg.message.type;
if (type == 0) {
//标记元素
let option = node.option;
let parameters = node.parameters;
//下面是让浏览器自动滚动到元素位置
if (option == 2 || option == 4 || option == 6 || option == 7) {
let xpath = parameters.xpath;
let parent_node = JSON.parse(msg.message.parentNode);
if (parameters.useLoop && option != 4 && option != 6) {
let parent_xpath = parent_node.parameters.xpath;
if (parent_node.parameters.loopType == 2) {
parent_xpath = parent_node.parameters.pathList
.split("\n")[0]
.trim();
}
xpath = parent_xpath + xpath;
}
if (xpath.includes("point(")) {
xpath = "//body";
}
let elementInfo = {iframe: parameters.iframe, xpath: xpath, id: -1};
//用于跳转到元素位置
let element = await findElementAcrossAllWindows(elementInfo);
} else if (option == 3) {
let params = parameters.params; //所有的提取数据参数
let param = params[0];
let xpath = param.relativeXPath;
if (param.relative) {
let parent_node = JSON.parse(msg.message.parentNode);
let parent_xpath = parent_node.parameters.xpath;
if (parent_node.parameters.loopType == 2) {
parent_xpath = parent_node.parameters.pathList
.split("\n")[0]
.trim();
}
xpath = parent_xpath + xpath;
}
let elementInfo = {iframe: param.iframe, xpath: xpath, id: -1};
let element = await findElementAcrossAllWindows(elementInfo);
} else if (option == 11) {
let params = parameters.params; //所有的提取数据参数
let i = parameters.index;
let param = params[i];
let xpath = param.relativeXPath;
if (param.relative) {
let parent_node = JSON.parse(msg.message.parentNode);
let parent_xpath = parent_node.parameters.xpath;
if (parent_node.parameters.loopType == 2) {
parent_xpath = parent_node.parameters.pathList
.split("\n")[0]
.trim();
}
xpath = parent_xpath + xpath;
}
let elementInfo = {iframe: param.iframe, xpath: xpath, id: -1};
let element = await findElementAcrossAllWindows(elementInfo);
} else if (option == 8) {
let loopType = parameters.loopType;
if (loopType <= 2) {
let xpath = "";
if (loopType <= 1) {
xpath = parameters.xpath;
} else if (loopType == 2) {
xpath = parameters.pathList.split("\n")[0].trim();
}
let elementInfo = {iframe: parameters.iframe, xpath: xpath, id: -1};
let element = await findElementAcrossAllWindows(elementInfo);
} else if (loopType == 5) {
//JavaScript命令返回值
let code = parameters.code;
let waitTime = parameters.waitTime;
let element = await driver.findElement(By.tagName("body"));
let outcome = await execute_js(code, element, waitTime);
if (!outcome || outcome == -1) {
notify_browser(
"目前页面中,设置的循环“" +
node.title +
"”的JavaScript条件不成立",
"The condition of the loop " +
node.title +
" is not met, skip this loop.",
"warning"
);
} else {
notify_browser(
"目前页面中,设置的循环“" + node.title + "”的JavaScript条件成立",
"The condition of the loop " +
node.title +
" is met, continue this loop.",
"success"
);
}
}
} else if (option == 10) {
//条件分支
let condition = parameters.class; //条件类型
let result = -1;
let additionalInfo = "";
if (condition == 5 || condition == 7) {
//JavaScript命令返回值
let code = parameters.code;
let waitTime = parameters.waitTime;
let element = await driver.findElement(By.tagName("body"));
if (condition == 7) {
let parent_node = JSON.parse(msg.message.parentNode);
let parent_xpath = parent_node.parameters.xpath;
if (parent_node.parameters.loopType == 2) {
parent_xpath = parent_node.parameters.pathList
.split("\n")[0]
.trim();
}
let elementInfo = {
iframe: parent_node.parameters.iframe,
xpath: parent_xpath,
id: -1,
};
element = await findElementAcrossAllWindows(elementInfo);
}
let outcome = await execute_js(code, element, waitTime);
if (!outcome) {
msg.message.result = 0; //条件不成立传入扩展
} else if (outcome == -1) {
msg.message.result = -1; //JS执行出错
} else {
msg.message.result = 1; //条件成立传入扩展
}
}
}
send_message_to_browser(JSON.stringify({type: "trial", message: msg}));
} else {
//试运行
try {
let flowchart_url = flowchart_window.webContents.getURL();
} catch {
flowchart_window = null;
}
if (flowchart_window == null) {
notify_flowchart(
"试运行功能只能在任务设计阶段,Chrome浏览器打开时使用!",
"The trial run function can only be used when designing tasks and opening in Chrome browser!",
"error"
);
} else {
notify_browser(
"正在试运行操作:" + node.title,
"Trying to run the operation: " + node.title,
"info"
);
let option = node.option;
let parameters = node.parameters;
let beforeJS = "";
let beforeJSWaitTime = 0;
let afterJS = "";
let afterJSWaitTime = 0;
try {
beforeJS = parameters.beforeJS;
beforeJSWaitTime = parameters.beforeJSWaitTime;
afterJS = parameters.afterJS;
afterJSWaitTime = parameters.afterJSWaitTime;
} catch (e) {
console.log(e);
}
if (option == 1) {
let url = parameters.links.split("\n")[0].trim();
if (parameters.useLoop) {
let parent_node = JSON.parse(msg.message.parentNode);
url = parent_node["parameters"]["textList"].split("\n")[0];
}
try {
await driver.get(url);
} catch (e) {
try {
await driver.switchTo().window(current_handle);
await driver.get(url);
} catch (e) {
let all_handles = await driver.getAllWindowHandles();
let handle = all_handles[all_handles.length - 1];
await driver.switchTo().window(handle);
await driver.get(url);
}
}
} else if (option == 2 || option == 7) {
//点击事件
let xpath = parameters.xpath;
let point = parameters.xpath;
if (xpath.includes("point(")) {
xpath = "//body";
}
let elementInfo = {iframe: parameters.iframe, xpath: xpath, id: -1};
if (parameters.useLoop && !parameters.xpath.includes("point(")) {
let parent_node = JSON.parse(msg.message.parentNode);
let parent_xpath = parent_node.parameters.xpath;
if (parent_node.parameters.loopType == 2) {
parent_xpath = parent_node.parameters.pathList
.split("\n")[0]
.trim();
}
elementInfo.xpath = parent_xpath + elementInfo.xpath;
}
let element = await findElementAcrossAllWindows(
elementInfo,
(notifyBrowser = false)
); //通过此函数找到元素并切换到对应的窗口
await execute_js(
parameters.beforeJS,
element,
parameters.beforeJSWaitTime
);
if (option == 2) {
if (parameters.xpath.includes("point(")) {
await click_element(element, point);
} else {
if (parameters.clickWay == 2){ //双击
await click_element(element, "double");
} else {
if (parameters.newTab == 1){
await click_element(element, "loopClickEvery"); //新标签页打开
} else {
await click_element(element); //单击
}
}
}
let alertHandleType = parameters.alertHandleType;
if (alertHandleType == 1) {
try {
await driver.switchTo().alert().accept();
} catch (e) {
console.log("No alert");
}
} else if (alertHandleType == 2) {
try {
await driver.switchTo().alert().dismiss();
} catch (e) {
console.log("No alert");
}
}
} else if (option == 7) {
await driver.actions().move({origin: element}).perform();
}
await execute_js(
parameters.afterJS,
element,
parameters.afterJSWaitTime
);
send_message_to_browser(JSON.stringify({type: "cancelSelection"}));
} else if (option == 3) {
//提取数据
notify_browser(
"提示:提取数据操作只能试运行设置的JavaScript语句,且只针对第一个匹配的元素。",
"Hint: can only test JavaScript statement set in the data extraction operation, and only for the first matching element.",
"info"
);
let params = parameters.params; //所有的提取数据参数
let not_found_xpaths = [];
for (let i = 0; i < params.length; i++) {
let param = params[i];
let xpath = param.relativeXPath;
if (param.relative) {
let parent_node = JSON.parse(msg.message.parentNode);
let parent_xpath = parent_node.parameters.xpath;
if (parent_node.parameters.loopType == 2) {
parent_xpath = parent_node.parameters.pathList
.split("\n")[0]
.trim();
}
xpath = parent_xpath + xpath;
}
let elementInfo = {iframe: param.iframe, xpath: xpath, id: -1};
let element = await findElementAcrossAllWindows(
elementInfo,
(notifyBrowser = false)
);
if (element != null) {
await execute_js(param.beforeJS, element, param.beforeJSWaitTime);
await execute_js(param.afterJS, element, param.afterJSWaitTime);
} else {
not_found_xpaths.push(xpath);
}
}
if (not_found_xpaths.length > 0) {
notify_browser(
"无法找到以下元素,请检查XPath是否正确:" +
not_found_xpaths.join("\n"),
"Cannot find the element, please check if the XPath is correct: " +
not_found_xpaths.join("\n"),
"warning"
);
}
} else if (option == 4) {
//键盘输入事件
let elementInfo = {
iframe: parameters.iframe,
xpath: parameters.xpath,
id: -1,
};
let value = node.parameters.value;
if (node.parameters.useLoop) {
let parent_node = JSON.parse(msg.message.parentNode);
value = parent_node["parameters"]["textList"].split("\n")[0];
let index = node.parameters.index;
if (index > 0) {
value = value.split("~")[index - 1];
}
}
let keyInfo = value;
let enter = false;
if (/<enter>/i.test(keyInfo)) {
keyInfo = keyInfo.replace(/<enter>/gi, "");
enter = true;
}
// 如果返回值中包含JS
if (/JS\(/i.test(keyInfo)) {
// 创建一个新的正则表达式来匹配JS语句
let pattern = /JS\("(.+?)"\)/gi;
// 找出所有的匹配项
let matches = [...keyInfo.matchAll(pattern)];
// 处理每一个匹配项
for (let match of matches) {
// 执行 JS 代码并等待结果
let jsReplacedText = await execute_js(match[1], null, 0);
// 替换匹配到的 JS 语句
keyInfo = keyInfo.replace(match[0], jsReplacedText.toString());
}
}
if (keyInfo.indexOf("Field[") >= 0 || keyInfo.indexOf("eval(") >= 0) {
//两秒后通知浏览器
await new Promise((resolve) => setTimeout(resolve, 2000));
notify_browser(
'检测到文字中包含Field[""]或eval(""),试运行时无法输入两项表达式的替换值,请在任务正式运行阶段测试是否有效。',
'Field[""] or eval("") is detected in the text, and the replacement value of the two expressions cannot be entered during trial operation. Please test whether it is valid in the formal call stage.',
"warning"
);
}
let element = await findElementAcrossAllWindows(
elementInfo,
(notifyBrowser = false)
);
await execute_js(beforeJS, element, beforeJSWaitTime);
await element.sendKeys(
Key.HOME,
Key.chord(Key.SHIFT, Key.END),
keyInfo
);
if (enter) {
await element.sendKeys(Key.ENTER);
}
await execute_js(afterJS, element, afterJSWaitTime);
} else if (option == 5) {
//自定义操作的JS代码
let code = parameters.code;
let codeMode = parameters.codeMode;
let waitTime = parameters.waitTime;
let element = await driver.findElement(By.tagName("body"));
if (codeMode == 0) {
let result = await execute_js(code, element, waitTime);
let level = "success";
if (result == -1) {
level = "info";
}
if (result != null) {
notify_browser(
"JavaScript操作返回结果:" + result,
"JavaScript operation returns result: " + result,
level
);
}
} else if (codeMode == 2) { // 循环内的JS代码
let parent_node = JSON.parse(msg.message.parentNode);
let parent_xpath = parent_node.parameters.xpath;
if (parent_node.parameters.loopType == 2) {
parent_xpath = parent_node.parameters.pathList
.split("\n")[0]
.trim();
}
let elementInfo = {iframe: parameters.iframe, xpath: parent_xpath, id: -1};
let element = await findElementAcrossAllWindows(
elementInfo, notifyBrowser = false); //通过此函数找到元素并切换到对应的窗口
let result = await execute_js(code, element, waitTime);
let level = "success";
if (result == -1) {
level = "info";
}
if (result != null) {
notify_browser(
"JavaScript操作返回结果:" + result,
"JavaScript operation returns result: " + result,
level
);
}
} else if (codeMode == 8) {
//刷新页面
try {
await driver.navigate().refresh();
} catch (e) {
try {
await driver.switchTo().window(current_handle);
await driver.navigate().refresh();
} catch (e) {
let all_handles = await driver.getAllWindowHandles();
let handle = all_handles[all_handles.length - 1];
await driver.switchTo().window(handle);
await driver.navigate().refresh();
}
}
}
} else if (option == 6) {
//切换下拉选项
let optionMode = parseInt(parameters.optionMode);
let optionValue = parameters.optionValue;
if (node.parameters.useLoop) {
let parent_node = JSON.parse(msg.message.parentNode);
optionValue = parent_node["parameters"]["textList"].split("\n")[0];
let index = node.parameters.index;
if (index > 0) {
optionValue = optionValue.split("~")[index - 1];
}
}
let elementInfo = {
iframe: parameters.iframe,
xpath: parameters.xpath,
id: -1,
};
let element = await findElementAcrossAllWindows(
elementInfo,
(notifyBrowser = false)
);
execute_js(beforeJS, element, beforeJSWaitTime);
let dropdown = new Select(element);
// Interacting with dropdown element based on optionMode
switch (optionMode) {
case 0: //切换到下一个选项
let script = `var options = arguments[0].options;
for (var i = 0; i < options.length; i++) {
if (options[i].selected) {
options[i].selected = false;
if (i == options.length - 1) {
options[0].selected = true;
} else {
options[i + 1].selected = true;
}
break;
}
}`;
await driver.executeScript(script, element);
break;
case 1:
await dropdown.selectByIndex(parseInt(optionValue));
break;
case 2:
await dropdown.selectByValue(optionValue);
break;
case 3:
await dropdown.selectByVisibleText(optionValue);
break;
default:
throw new Error("Invalid option mode");
}
execute_js(afterJS, element, afterJSWaitTime);
} else if (option == 11) {
//单个提取数据参数
// notify_browser(
// "提示:提取数据字段的试运行操作只针对第一个匹配的元素。",
// "Hint: can only test the trial operation of the data extraction field for the first matching element.",
// "info"
// );
let params = parameters.params; //所有的提取数据参数
let i = parameters.index;
let param = params[i];
let xpath = param.relativeXPath;
if (param.relative) {
let parent_node = JSON.parse(msg.message.parentNode);
let parent_xpath = parent_node.parameters.xpath;
if (parent_node.parameters.loopType == 2) {
parent_xpath = parent_node.parameters.pathList
.split("\n")[0]
.trim();
}
xpath = parent_xpath + xpath;
}
let elementInfo = {iframe: param.iframe, xpath: xpath, id: -1};
let element = await findElementAcrossAllWindows(elementInfo);
if (element != null) {
await execute_js(param.beforeJS, element, param.beforeJSWaitTime);
if (param.contentType == 0) {
let result = await element.getText(); // 获取元素及其子元素的文本内容
if (param.nodeType == 2) { //链接地址
result = await element.getAttribute("href");
notify_browser("获取的链接地址:" + result, "Link URL obtained: " + result, "success")
} else if (param.nodeType == 3) { //表单值
result = await element.getAttribute("value");
notify_browser("获取的表单值:" + result, "Form value obtained: " + result, "success")
} else if (param.nodeType == 4) { //图片地址
result = await element.getAttribute("src");
notify_browser("获取的图片地址:" + result, "Image URL obtained: " + result, "success")
} else {
notify_browser("获取的文本内容:" + result, "Text content obtained: " + result, "success");
}
} else if (param.contentType == 1) {
// 对于Selenium,获取不包括子元素的文本可能需要特殊处理,这里假设element是父元素
let command = 'var arr = [];\
var content = arguments[0];\
for(var i = 0, len = content.childNodes.length; i < len; i++) {\
if(content.childNodes[i].nodeType === 3){ \
arr.push(content.childNodes[i].nodeValue);\
}\
}\
var str = arr.join(" "); \
return str;'
let result = await execute_js(command, element, 0);
result = result.replace(/\n/g, "").replace(/\s+/g, " ");
notify_browser("获取的内容:" + result, "Content obtained: " + result, "success");
} else if (param.contentType == 2) {
let result = await element.getAttribute('innerHTML'); // 获取元素的内部HTML内容
notify_browser("获取的innerHTML:" + result, "innerHTML obtained: " + result, "success");
} else if (param.contentType == 3) {
let result = await element.getAttribute('outerHTML'); // 获取元素及其内容的HTML表示
notify_browser("获取的outerHTML:" + result, "outerHTML obtained: " + result, "success");
} else if (param.contentType == 4) {
let result = await element.getCssValue('background-image'); // 获取元素的背景图片地址
notify_browser("获取的背景图片地址:" + result, "Background image URL obtained: " + result, "success");
} else if (param.contentType == 5) {
let result = await driver.getCurrentUrl(); // 获取页面的网址
notify_browser("获取的页面网址:" + result, "Page URL obtained: " + result, "success");
} else if (param.contentType == 6) { //页面标题
let result = await driver.getTitle();
notify_browser("获取的页面标题:" + result, "Page title obtained: " + result, "success");
} else if (param.contentType == 9) { //针对元素的JavaScript代码返回值
let result = await execute_js(param.JS, element);
let level = "success";
if (result == -1) {
level = "info";
}
if (result != null) {
notify_browser(
"JavaScript操作返回结果:" + result,
"JavaScript operation returns result: " + result,
level
);
}
} else if (param.contentType == 10) {
// 当前选择框选中的选项值
let result = await element.getAttribute("value");
notify_browser(
"获取的选项值:" + result,
"Option value obtained: " + result,
"success"
);
} else if (param.contentType == 11) {
// 当前选择框选中的选项文本
let selectElement = new Select(element);
// 等待选项变得可选,这是可选的,根据页面加载情况
await driver.wait(until.elementIsEnabled(element));
// 获取当前选中的选项元素
let selectedOption = await selectElement.getFirstSelectedOption();
// 获取选项的文本内容