-
Notifications
You must be signed in to change notification settings - Fork 28
/
Webdriver4D.pas
1969 lines (1822 loc) · 47.5 KB
/
Webdriver4D.pas
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
unit Webdriver4D;
interface
uses
Classes, SysUtils, Windows, Contnrs, Vcl.Graphics, WD_http,
{$IFDEF FPC} {$ELSE} WD_httpDelphi, {$ENDIF}
//{$IFDEF FPC} {$ELSE} WD_httpCis, {$ENDIF}
JsonDataObjects, Winapi.ShlObj;
type
TWebDriverClass=class of TWebDriver;
TCommandType = (cGet, cPost, cDelete);
TDriverType = (btPhantomjs, btIE, btFirefox, btChrome,btEdge);
TWebDriver = class;
TWebElement = packed record
private
FKeyName: string;
FUsingName: string;
FWebDriver: TWebDriver;
function GetValue: string;
function GetTagName: string;
function GetSize: string;
function GetText: string;
public
W3C: Boolean;
ElementData: string;
function AttributeValue(aName: string): string;
function PropertyValue(aName: string): string;
procedure Clear;
procedure Click;
function IsEmpty: Boolean;
function Location: string;
procedure ScreenShot(const FileName: string); overload;
procedure ScreenShot(var bmp: TBitmap); overload;
procedure ScreenShot2(var bmp: TBitmap); overload; // 有的浏览器不支持
procedure SendKey(Key: string);
property WebDriver: TWebDriver read FWebDriver write FWebDriver;
property UsingName: string read FUsingName write FUsingName;
property KeyName: string read FKeyName write FKeyName;
property Value: string read GetValue; // 元件ID值
property TagName: string read GetTagName;
property Size: string read GetSize;
property Text: string read GetText;
end;
TWebElements = packed record
private
FKeyName: string;
FUsingName: string;
FWebDriver: TWebDriver;
function GetCount: Integer;
function GetItems(Index: Integer): TWebElement;
public
W3C: Boolean;
ElementsData: String;
property KeyName: string read FKeyName write FKeyName;
property UsingName: string read FUsingName write FUsingName;
property WebDriver: TWebDriver read FWebDriver write FWebDriver;
property Count: Integer read GetCount;
property Items[Index: Integer]: TWebElement read GetItems;
end;
TExecCommandEvent = procedure(response: string) of object;
TWebDriver = class(TComponent)
private
FAddress: string;
FCmd: TDriverCommand;
FErrorMessage: string;
FOnResponse: TExecCommandEvent;
FPopup_Error: Boolean;
FProcessInfo: TProcessInformation;
FStartupInfo: TStartupInfo;
function GetDriverIsRunning: Boolean;
function GetHasError: Boolean;
function GetHost: string;
function GetTimeout: Integer;
procedure SetTimeout(const Value: Integer);
strict protected
FDriverName: string;
FLogFile: string;
FPath: string;
FPort: Integer;
FSessionID: string;
FW3C: Boolean;
function BuildParams: string; virtual;
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
function ExecuteCommand(const CommandType: TCommandType;
const Command: string; const Param: string = ''): string;
function ProcResponse(const Resp: string): string;
procedure CutImage(Pic: string; X, Y, Width, Height: Integer;
var bmp: TBitmap);
procedure Base64ToBmp(Pic: string; var bmp: TBitmap);
procedure BmpToPng(bmp: TBitmap; const FileName: string);
procedure StartDriver(const ExeName: string;
const Args: string = ''); virtual;
procedure Assign(Source: TPersistent); override;
procedure CloseWindow(ParamSessionID: string = '');
function GetAllCookie: string;
function GetAllCookieJsonArray: string;
function GetCookieByName(cookieName: string): string;
function AddCookie(cookieName, cookieValue: string): string;
procedure DeleteAllCookie;
procedure DeleteCookie(const cookieName: string);
function FindElement(UsingName, KeyName: string): TWebElement;
function FindElementByID(const ID: string): TWebElement;
function FindElementByTag(const TagName: string): TWebElement;
function FindElementByClassName(const ClasName: string): TWebElement;
function FindElementByLinkText(const LinkText: string): TWebElement;
function FindElementByXPath(XPath: string): TWebElement;
function FindElements(const UsingName, KeyName: string): TWebElements;
function FindElementsByXPath(XPath: string): TWebElements;
function FindElementsByTag(const TagName: string): TWebElements;
function FindElementsByLinkText(const LinkText: string): TWebElements;
function FindElementsByID(const ID: string): TWebElements;
function FindElementsByClassName(const ClasName: string): TWebElements;
function GetCurrentWindowHandle: string;
procedure GetURL(const URL: string);
function GetCurUrl: string;
function NewSession: string; virtual; abstract;
procedure DeleteSession(ParamSessionID: string = '');
function GetDocument: string;
function GetAllSession: string;
procedure Set_Window_Size(const Width, Height: Integer;
WindowHandle: string = 'current');
function ExecuteScript(const Script: string; const Args: string = '[]')
: string; virtual;
procedure ExecuteScriptByASync(const Script: string;
const Args: string = '[]'); virtual;
procedure Implicitly_Wait(const waitTime: Double);
procedure PageLoadTimeout(const Timeout: Integer);
procedure Quit;
procedure Refresh(ParamSessionID: string = '');
procedure SaveCurDocToFile(const FileName: string);
procedure ScreenShot(var bmp: TBitmap); overload;
procedure ScreenShot(const FileName: string); overload;
procedure SwitchToFrame(const FrameID: string); virtual;
procedure SwitchToParentFrame; virtual;
procedure TerminateWebDriver;
procedure WaitForLoaded;
property ErrorMessage: string read FErrorMessage;
property HasError: Boolean read GetHasError;
property LogFile: string read FLogFile write FLogFile;
property Host: string read GetHost;
property Address: string read FAddress write FAddress;
property Cmd: TDriverCommand read FCmd write FCmd;
property DriverIsRunning: Boolean read GetDriverIsRunning;
property DriverName: string read FDriverName;
property Port: Integer read FPort write FPort;
property Path: string read FPath write FPath;
property Popup_Error: Boolean read FPopup_Error write FPopup_Error;
property SessionID: string read FSessionID write FSessionID;
property W3C: Boolean read FW3C;
published
procedure Clear;
property Timeout: Integer read GetTimeout write SetTimeout;
property OnResponse: TExecCommandEvent read FOnResponse write FOnResponse;
end;
TPhantomjs = class(TWebDriver)
private
FCookieFiles: string;
FDiskCache: Boolean;
FDiskCachePath: string;
strict protected
function BuildParams: string; override;
public
constructor Create(AOwner: TComponent); override;
procedure Assign(Source: TPersistent); override;
function ExecuteScript(const Script: string; const Args: string = '[]')
: string; override;
function Execute_Phantom_Script(const Script: string; const Args: string =
'[]'): string;
function NewSession: string; override;
property CookieFiles: string read FCookieFiles write FCookieFiles;
property DiskCache: Boolean read FDiskCache write FDiskCache;
property DiskCachePath: string read FDiskCachePath write FDiskCachePath;
end;
TIEDriver = class(TWebDriver)
strict protected
function BuildParams: string; override;
public
constructor Create(AOwner: TComponent); override;
function NewSession: string; override;
end;
TFireFoxDriver = class(TWebDriver)
private
FBrowserFileName: string;
FnewVersion: Boolean;
strict protected
function BuildParams: string; override;
public
constructor Create(AOwner: TComponent); override;
function NewSession: string; override;
procedure StartDriver(const ExeName: string;
const Args: string = ''); override;
property BrowserFileName: string read FBrowserFileName
write FBrowserFileName;
property newVersion: Boolean read FnewVersion write FnewVersion;
end;
TChromeDriver = class(TWebDriver)
strict protected
function BuildParams: string; override;
public
constructor Create(AOwner: TComponent); override;
function NewSession: string; override;
procedure StartDriver(const ExeName: string;
const Args: string = ''); override;
end;
TEdgeDriver = class(TWebDriver)
strict protected
function BuildParams: string; override;
public
constructor Create(AOwner: TComponent); override;
function NewSession: string; override;
procedure SwitchToFrame(const FrameID: string); override;
end;
implementation
uses
System.NetEncoding, Vcl.Imaging.pngimage, System.StrUtils, Winapi.TlHelp32,
System.Variants;
constructor TWebDriver.Create(AOwner: TComponent);
begin
inherited;
FillChar(FProcessInfo, SizeOf(FProcessInfo), 0);
FAddress := '127.0.0.1';
FLogFile := '';
FPath := '';
FErrorMessage := '';
FW3C := False;
FPopup_Error := True;
{$IFDEF FPC}
{$ELSE}
FCmd := TDelphiCommand.Create(self);
{$ENDIF}
end;
destructor TWebDriver.Destroy;
begin
if FProcessInfo.hProcess <> 0 then
TerminateWebDriver;
inherited;
end;
procedure TWebDriver.Assign(Source: TPersistent);
var
WD: TWebDriver;
begin
inherited;
if Source is TWebDriver then
begin
WD := Source as TWebDriver;
self.Address := WD.Address;
self.Port := WD.Port;
self.Path := WD.Path;
self.Timeout := WD.Timeout;
end;
end;
function TWebDriver.BuildParams: string;
begin
end;
procedure TWebDriver.CloseWindow(ParamSessionID: string = '');
var
Command: string;
begin
if ParamSessionID <> '' then
Command := Host + '/session/' + ParamSessionID + '/window'
else
Command := Host + '/session/' + FSessionID + '/window';
ExecuteCommand(cDelete, Command);
end;
procedure TWebDriver.CutImage(Pic: string; X, Y, Width, Height: Integer;
var bmp: TBitmap);
var
png: TPngImage;
Encd: TBase64Encoding;
Stream: TMemoryStream;
Byts: TBytes;
REctS, REctD: TRect;
begin
Encd := TBase64Encoding.Create;
Stream := TMemoryStream.Create;
png := TPngImage.Create;
try
Byts := Encd.DecodeStringToBytes(Pic);
Stream.Write(Byts[0], Length(Byts));
Stream.Position := 0;
png.LoadFromStream(Stream);
REctS.Left := X;
REctS.Top := Y;
REctS.Width := Width;
REctS.Height := Height;
REctD.Left := 0;
REctD.Top := 0;
REctD.Width := Width;
REctD.Height := Height;
bmp.Width := Width;
bmp.Height := Height;
bmp.Canvas.CopyRect(REctD, png.Canvas, REctS);
// bitblt(pngd.Canvas.Handle,0,0,Width,height,png.Canvas.Handle,X,Y,SRCCOPY);
finally
FreeAndNil(png);
FreeAndNil(Stream);
FreeAndNil(Encd);
end;
end;
procedure TWebDriver.DeleteSession(ParamSessionID: string = '');
var
Command: string;
begin
if ParamSessionID <> '' then
begin
Command := Host + '/session/' + ParamSessionID;
end
else
begin
Command := Host + '/session/' + FSessionID;
end;
ExecuteCommand(cDelete, Command);
end;
function TWebDriver.ExecuteScript(const Script: string;
const Args: string = '[]'): string;
var
Command: string;
Data: string;
Resp: string;
Json: TJsonObject;
begin
Json := TJsonObject.Create;
try
Command := Host + '/session/' + FSessionID + '/execute/sync';
Json.S['script'] := Script;
Json.A['args'].FromJSON(Args);
Data := Json.ToJSON();
Resp := ExecuteCommand(cPost, Command, Data);
result := ProcResponse(Resp);
Finally
FreeAndNil(Json);
end;
end;
function TWebDriver.FindElementByID(const ID: string): TWebElement;
begin
result := FindElement('id', ID);
end;
function TWebDriver.FindElementByTag(const TagName: string): TWebElement;
begin
result := FindElement('tag name', TagName);
end;
function TWebDriver.FindElementByClassName(const ClasName: string): TWebElement;
begin
result := FindElement('class name', ClassName);
end;
function TWebDriver.FindElement(UsingName, KeyName: string): TWebElement;
var
Command: string;
Data: string;
Resp: string;
JsonData: string;
Json: TJsonObject;
begin
Command := Host + '/session/' + FSessionID + '/element';
if FW3C then
begin
if SameText(UsingName, 'id') then
begin
UsingName := 'css selector';
KeyName := format('[id="%s" ]', [KeyName]);
end
else if SameText(UsingName, 'tag name') then
begin
UsingName := 'css selector';
end
else if SameText(UsingName, 'class name') then
begin
UsingName := 'css selector';
KeyName := format('.%s', [KeyName]);
end
else if SameText(UsingName, 'name') then
begin
UsingName := 'css selector';
KeyName := format('[name="%s"]', [KeyName]);
end;
end;
Json := TJsonObject.Create;
try
Json.S['using'] := UsingName;
Json.S['value'] := KeyName;
Data := Json.ToJSON();
finally
Json.Free;
end;
Resp := ExecuteCommand(cPost, Command, Data);
JsonData := ProcResponse(Resp);
result.WebDriver := self;
result.UsingName := UsingName;
result.KeyName := KeyName;
if not HasError then
begin
result.W3C := FW3C;
result.ElementData := JsonData;
end
else
result.ElementData := '';
end;
function TWebDriver.FindElementByLinkText(const LinkText: string): TWebElement;
begin
result := FindElement('link text', LinkText);
end;
function TWebDriver.FindElementByXPath(XPath: string): TWebElement;
begin
result := FindElement('xpath', XPath);
end;
function TWebDriver.GetAllSession: string;
var
Command: string;
Resp: string;
begin
Command := Host + '/sessions';
Resp := ExecuteCommand(cGet, Command);
if Resp <> '' then
begin
result := ProcResponse(Resp);
end
else
begin
result := '';
end;
end;
function TWebDriver.GetCurrentWindowHandle: string;
var
Command: string;
Resp: string;
begin
Command := Host + '/session/' + FSessionID + '/window_handle';
Resp := ExecuteCommand(cGet, Command);
result := ProcResponse(Resp);
end;
function TWebDriver.GetHost: string;
begin
result := format('http://%s:%d%s', [FAddress, FPort, FPath]);
end;
procedure TWebDriver.GetURL(const URL: string);
var
Command: string;
Data: string;
Resp: string;
Json: TJsonObject;
begin
Command := Host + '/session/' + FSessionID + '/url';
Json := TJsonObject.Create;
try
Json.S['url'] := URL;
Json.S['sessionid'] := FSessionID;
Data := Json.ToJSON();
Resp := ExecuteCommand(cPost, Command, Data);
ProcResponse(Resp);
if not HasError then
WaitForLoaded;
finally
FreeAndNil(Json);
end;
end;
procedure TWebDriver.Implicitly_Wait(const waitTime: Double);
var
Command: string;
Data: string;
Resp: string;
Json: TJsonObject;
begin
Json := TJsonObject.Create;
try
if W3C then
begin
Command := Host + '/session/' + FSessionID + '/timeouts';
Json.F['implicit'] := waitTime;
end
else
begin
Command := Host + '/session/' + FSessionID + '/timeouts/implicit_wait';
Json.F['ms'] := waitTime;
Json.S['session'] := FSessionID;
Data := Json.ToJSON();
end;
Resp := ExecuteCommand(cPost, Command, Data);
ProcResponse(Resp);
finally
FreeAndNil(Json);
end;
end;
procedure TWebDriver.Quit;
begin
if FSessionID <> '' then
begin
DeleteSession(FSessionID);
FSessionID := '';
end;
end;
procedure TWebDriver.Refresh(ParamSessionID: string = '');
var
Command: string;
Data: string;
Resp: string;
Json: TJsonObject;
begin
Json := TJsonObject.Create;
try
if ParamSessionID <> '' then
Command := Host + '/session/' + ParamSessionID + '/refresh'
else
Command := Host + '/session/' + FSessionID + '/refresh';
Json.S['sessionid'] := FSessionID;
Data := Json.ToJSON();
Resp := ExecuteCommand(cPost, Command, Data);
ProcResponse(Resp);
finally
FreeAndNil(Json);
end;
end;
procedure TWebDriver.StartDriver(const ExeName: string;
const Args: string = '');
var
Command: string;
begin
if not FileExists(ExeName) then
raise Exception.Create('driver file not exists.' + ExeName);
FDriverName := ExeName;
if FProcessInfo.hProcess <> 0 then
Exit;
FillChar(FStartupInfo, SizeOf(FStartupInfo), 0);
FillChar(FProcessInfo, SizeOf(FProcessInfo), 0);
FStartupInfo.dwFlags := STARTF_USESHOWWINDOW;
FStartupInfo.wShowWindow := SW_HIDE;
if Args = '' then
Command := self.BuildParams
else
Command := Args;
if CreateProcess(nil, Pchar(ExeName + ' ' + Command), nil, nil, False,
NORMAL_PRIORITY_CLASS, nil, nil, FStartupInfo, FProcessInfo) then
begin
end;
end;
function TWebDriver.FindElementsByXPath(XPath: string): TWebElements;
begin
result := FindElements('xpath', XPath);
end;
function TWebDriver.FindElementsByTag(const TagName: string): TWebElements;
begin
result := FindElements('tag name', TagName);
end;
function TWebDriver.FindElementsByLinkText(const LinkText: string)
: TWebElements;
begin
result := FindElements('link text', LinkText);
end;
function TWebDriver.FindElementsByID(const ID: string): TWebElements;
begin
result := FindElements('id', ID);
end;
function TWebDriver.FindElementsByClassName(const ClasName: string)
: TWebElements;
begin
result := FindElements('class name', ClassName);
end;
function TWebDriver.FindElements(const UsingName, KeyName: string)
: TWebElements;
var
Command: string;
Data: string;
Resp: string;
Json: TJsonObject;
JsonData: string;
begin
Json := TJsonObject.Create;
try
Command := Host + '/session/' + FSessionID + '/elements';
Json.S['value'] := KeyName;
Json.S['sessionid'] := FSessionID;
Json.S['using'] := UsingName;
Data := Json.ToJSON(False);
finally
FreeAndNil(Json);
end;
Resp := ExecuteCommand(cPost, Command, Data);
JsonData := ProcResponse(Resp);
result.WebDriver := self;
result.UsingName := UsingName;
result.KeyName := KeyName;
if not HasError then
begin
result.W3C := FW3C;
result.ElementsData := JsonData;
end
else
result.ElementsData := '';
end;
procedure TWebDriver.Set_Window_Size(const Width, Height: Integer;
WindowHandle: string = 'current');
var
Command: string;
Data: string;
Resp: string;
Json: TJsonObject;
begin
Json := TJsonObject.Create;
try
if W3C then
begin
Command := Host + '/session/' + FSessionID + '/window/rect';
Json.I['width'] := Width;
Json.I['height'] := Height;
Json.S['windowHandle'] := WindowHandle;
end
else
begin
Command := Host + '/session/' + FSessionID + '/window/' + WindowHandle
+ '/size';
Json.I['width'] := Width;
Json.I['height'] := Height;
end;
Data := Json.ToJSON();
Resp := ExecuteCommand(cPost, Command, Data);
ProcResponse(Resp);
finally
FreeAndNil(Json);
end;
end;
procedure TWebDriver.TerminateWebDriver;
begin
TerminateProcess(FProcessInfo.hProcess, 0);
FillChar(FStartupInfo, SizeOf(FStartupInfo), 0);
FillChar(FProcessInfo, SizeOf(FProcessInfo), 0);
end;
procedure TWebDriver.Clear;
var
AllSession: string;
Json: TJsonArray;
Session: string;
I: Integer;
begin
AllSession := GetAllSession;
Json := TJsonArray.Create;
try
if AllSession <> '' then
begin
Json.FromJSON(AllSession);
for I := 0 to Json.Count - 1 do
begin
Session := Json.O[I].S['id'];
CloseWindow(Session);
DeleteSession(Session);
end;
end;
finally
FreeAndNil(Json);
end;
end;
procedure TWebDriver.DeleteAllCookie;
var
Command: string;
begin
Command := Host + '/session/' + FSessionID + '/cookie';
ExecuteCommand(cDelete, Command)
end;
procedure TWebDriver.DeleteCookie(const cookieName: string);
var
Command: string;
begin
Command := Host + '/session/' + FSessionID + '/cookie' + '/' + cookieName;
ExecuteCommand(cDelete, Command);
end;
function TWebDriver.GetAllCookie: string;
var
S: string;
I: Integer;
aryJson: TJsonArray;
tmpJson: TJsonObject;
begin
result := '';
S := GetAllCookieJsonArray;
aryJson := TJsonBaseObject.Parse(S) as TJsonArray;
if aryJson <> nil then
begin
// 数组JSON
for I := 0 to aryJson.Count - 1 do
begin
tmpJson := aryJson.O[I];
if result = '' then
result := tmpJson.S['name'] + '=' + tmpJson.S['value']
else
result := result + '; ' + tmpJson.S['name'] + '=' + tmpJson.S['value'];
end;
aryJson.Free;
end;
end;
function TWebDriver.GetTimeout: Integer;
begin
result := FCmd.Timeout;
end;
procedure TWebDriver.PageLoadTimeout(const Timeout: Integer);
var
Command: string;
Data: string;
Resp: string;
Json: TJsonObject;
begin
Json := TJsonObject.Create;
try
Command := Host + '/session/' + FSessionID + '/timeouts';
Json.Clear;
Json.S['name'] := 'pageLoad';
Json.I['value'] := Timeout;
Data := Json.ToJSON(False);
finally
FreeAndNil(Json);
end;
Resp := ExecuteCommand(cPost, Command, Data);
ProcResponse(Resp);
end;
function TWebDriver.AddCookie(cookieName, cookieValue: string): string;
var
Command: string;
Data: string;
Resp: string;
Json, ckJson: TJsonObject;
begin
Json := TJsonObject.Create;
try
ckJson := Json.O['cookie'];
ckJson.S['name'] := cookieName;
ckJson.S['value'] := cookieValue;
Command := Host + '/session/' + FSessionID + '/cookie';
Data := Json.ToJSON(True);
finally
FreeAndNil(Json);
end;
Resp := ExecuteCommand(cPost, Command, Data);
ProcResponse(Resp);
end;
procedure TWebDriver.BmpToPng(bmp: TBitmap; const FileName: string);
var
png: TPngImage;
begin
png := TPngImage.Create;
try
png.Assign(bmp);
png.SaveToFile(FileName);
finally
FreeAndNil(png);
end;
end;
procedure TWebDriver.Base64ToBmp(Pic: string; var bmp: TBitmap);
var
png: TPngImage;
Encd: TBase64Encoding;
Stream: TMemoryStream;
Byts: TBytes;
REctS, REctD: TRect;
begin
Encd := TBase64Encoding.Create;
Stream := TMemoryStream.Create;
png := TPngImage.Create;
try
Byts := Encd.DecodeStringToBytes(Pic);
Stream.Write(Byts[0], Length(Byts));
Stream.Position := 0;
png.LoadFromStream(Stream);
REctS.Left := 0;
REctS.Top := 0;
REctS.Width := png.Width;
REctS.Height := png.Height;
REctD.Left := 0;
REctD.Top := 0;
REctD.Width := png.Width;
REctD.Height := png.Height;
bmp.Width := png.Width;
bmp.Height := png.Height;
bmp.Canvas.CopyRect(REctD, png.Canvas, REctS);
// bitblt(pngd.Canvas.Handle,0,0,Width,height,png.Canvas.Handle,X,Y,SRCCOPY);
finally
FreeAndNil(png);
FreeAndNil(Stream);
FreeAndNil(Encd);
end;
end;
function TWebDriver.ExecuteCommand(const CommandType: TCommandType;
const Command: string; const Param: string = ''): string;
begin
FErrorMessage := '';
case CommandType of
cGet:
begin
result := FCmd.ExecuteGet(Command);
end;
cPost:
begin
result := FCmd.ExecutePost(Command, Param);
end;
cDelete:
begin
FCmd.ExecuteDelete(Command);
end;
end;
if Assigned(FOnResponse) then
begin
FOnResponse(result);
end;
end;
procedure TWebDriver.ExecuteScriptByASync(const Script: string;
const Args: string = '[]');
var
Command: string;
Data: string;
Resp: string;
Json: TJsonObject;
begin
Json := TJsonObject.Create;
try
Command := Host + '/session/' + FSessionID + '/execute/async';
Json.S['script'] := Script;
Json.A['args'].FromJSON(Args);
Json.S['sessionId'] := FSessionID;
Data := Json.ToJSON();
Resp := ExecuteCommand(cPost, Command, Data);
ProcResponse(Resp);
Finally
FreeAndNil(Json);
end;
end;
function TWebDriver.GetDocument: string;
var
Command: string;
begin
result := '';
if FSessionID <> '' then
begin
Command := Host + '/session/' + FSessionID + '/source';
result := ProcResponse(ExecuteCommand(cGet, Command));
end;
end;
function TWebDriver.GetAllCookieJsonArray: string;
var
Command: string;
Resp: string;
begin
Command := Host + '/session/' + FSessionID + '/cookie';
Resp := ExecuteCommand(cGet, Command);
if Resp <> '' then
result := ProcResponse(Resp)
else
result := '[]';
end;
function TWebDriver.GetCookieByName(cookieName: string): string;
var
Command: string;
Resp: string;
S: string;
I: Integer;
aryJson: TJsonArray;
tmpJson: TJsonObject;
begin
// 用标准接口返回是错误,故用此方法
Command := Host + '/session/' + FSessionID + '/cookie';
Resp := ExecuteCommand(cGet, Command);
if Resp <> '' then
S := ProcResponse(Resp)
else
S := '[]';
aryJson := TJsonBaseObject.Parse(S) as TJsonArray;
if aryJson <> nil then
begin
// 数组JSON
for I := 0 to aryJson.Count - 1 do
begin
tmpJson := aryJson.O[I];
if tmpJson.S['name'] = cookieName then
begin
result := tmpJson.S['value'];
break;
end;
end;
aryJson.Free;
end;
end;
function TWebDriver.GetCurUrl: string;
var
Command: string;
Resp: string;
begin
Command := Host + '/session/' + FSessionID + '/url';
Resp := ExecuteCommand(cGet, Command);
result := ProcResponse(Resp);
end;
function TWebDriver.GetDriverIsRunning: Boolean;
begin
result := FProcessInfo.hProcess <> 0;
end;
function TWebDriver.GetHasError: Boolean;
begin
result := FErrorMessage <> '';
end;
function TWebDriver.ProcResponse(const Resp: string): string;
var
Json, Obj: TJsonObject;
jType: TJsonDataType;
begin
FErrorMessage := '';
Json := TJsonObject.Create;
try
if Resp <> '' then
begin
Json.FromJSON(Resp);
if Json.Contains('value') then
begin
// success
jType := Json.Types['value'];
case jType of
jdtString, jdtInt, jdtLong, jdtULong, jdtFloat, jdtDateTime, jdtBool: