-
Notifications
You must be signed in to change notification settings - Fork 0
/
Browser.cs
9298 lines (8579 loc) · 481 KB
/
Browser.cs
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
//using static System.Net.Mime.MediaTypeNames;
using Newtonsoft.Json.Linq;
using OpenQA.Selenium;
using OpenQA.Selenium.Chrome;
using OpenQA.Selenium.DevTools;
using OpenQA.Selenium.Interactions;
using OpenQA.Selenium.Remote;
using OpenQA.Selenium.Support.UI;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics;
using System.Drawing;
using System.Globalization;
//https://dotblogs.com.tw/supergary/2020/10/29/selenium#images-3
using System.IO;
using System.Linq;
using System.Media;
//using System.Net;
//using System.Net.NetworkInformation;
using System.Runtime.InteropServices;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
using System.Web;
using System.Windows.Automation;
using System.Windows.Forms;
using WebSocketSharp;
using WindowsFormsApp1;
//using static System.Net.Mime.MediaTypeNames;
using forms = System.Windows.Forms;
using selm = OpenQA.Selenium;
namespace TextForCtext
{
class Browser
{
/// <summary>
/// 作為模擬「參數」供給此類別操作時參考
/// </summary>
private static Form1 frm;
/// <summary>
/// 指定延長等待開啟舊檔對話方塊出現的時間(毫秒數)
/// 在 textBox2 中輸入「ws」(wait second)以設定此值
/// 若要縮減時間,請指定負數
/// </summary>
internal static int Extend_the_wait_time_for_the_Open_Old_File_dialog_box_to_appear_Millisecond = 0;
/// <summary>
/// 指定等待OCR諸過程最久的時間(以秒數)
/// 在 textBox2 中輸入「wO」(wait second)以設定此值
/// </summary>
internal static int OCR_wait_time_Top_Limit_second = 15;
/// <summary>
/// 記錄當前對外IP位置
/// </summary>
internal static string CurrentIP;
/// <summary>
/// 記錄切換VPN的次數
/// </summary>
internal static int VPNSwitchedTimer = 0;
/// <summary>
/// 因為剪貼簿的操作頻繁,故以此記下要貼去簡單修改模式方塊中的文字內容,以免被干擾
/// </summary>
internal static string TextPatst2Quick_editBox = "";
//readonly Form1 Form1 = Application.OpenForms.Count > 0 ? Application.OpenForms[0] as Form1 : null;
/*如何取得作用中的表單? 20230312 chatGPT大菩薩:
您好!如果您使用的是 Windows.Forms,您可以使用以下方法来获取当前处于活动状态的表单:
Form activeForm = Form.ActiveForm;
这将返回当前活动的表单对象,您可以使用该对象的属性和方法来访问和操作该表单。
请注意,此方法仅适用于您的应用程序具有焦点,并且该方法将返回具有焦点的表单。如果没有焦点的表单,该方法将返回 null。
如果您想要获取应用程序中的其他表单而不是当前处于活动状态的表单,您可以使用以下方法之一:
使用表单的名称或类型来查找表单:
Form myForm = Application.OpenForms["MyFormName"];
或
Form myForm = Application.OpenForms.OfType<MyFormType>().FirstOrDefault();
在您的代码中保留对表单对象的引用,并在需要时使用该引用来访问该表单。
*/
//creedit
public Browser(Form1 form)
{
ActiveForm1 = form;
}
// 創建Chrome驅動程序對象
//selm.IWebDriver driver=driverNew();
//internal static selm.IWebDriver driver=driverNew();
//internal static ChromeDriver driver = driverNew();
static string browserName = Form1.defaultBrowserName;// "chrome";
internal static string chrome_path = Form1.getDefaultBrowserEXE();
static string user_data_dir;
static string downloadDirectory_Chrome;//= "";
static Process[] chromeProcessInstances = Process.GetProcessesByName(browserName);//("chrome");
internal static ChromeDriverService driverService;
internal static ChromeOptions options = chromeOptions(chrome_path);
internal static ChromeDriver driver = initiateChromeDriver().Item1;
internal static RemoteWebDriver driverRemote = initiateChromeDriver().Item2;
/* 20230309 creedit with chatGPT大菩薩:C# Enum Values:
* 那元素值可以是string型別的嗎?
在C#中,enum元素值只能是整數型別,例如int、short或byte等。因此,無法直接指定字符串作為enum元素的值。如果需要將字符串映射到enum值,可以使用另一個類型,例如字典或自定義類型,將字符串映射到對應的enum值。在這種情況下,需要確保映射的字符串與enum元素的名稱相對應,以便能夠在代碼中使用enum元素。
孫守真
如我想把一些常用的網站網址作為 enum 就不如作成 Dictionary 囉?
如果你想要將常用網站的網址作為枚舉值使用,並且需要對這些值進行比較和操作,則枚舉可能是一個不錯的選擇。但如果只是需要一個可以將網址映射到對應值的結構,那麼使用字典可能更適合。以下是兩者使用的建議:
Enum:如果你需要一個有限的、可枚舉的值集合,而這些值具有特定的順序和整數值(例如,星期幾或方向),那麼使用枚舉可能是一個很好的選擇。但是,如果你想要將字符串作為值使用,或者值的集合需要動態擴展,那麼枚舉可能不是最好的選擇。
Dictionary:如果你需要一個可以將一個值映射到另一個值的結構,並且這個映射可以動態擴展,那麼字典可能是最好的選擇。字典可以存儲任意類型的值,包括字符串,並且可以根據需要動態添加或刪除鍵值對。使用字典,你可以輕鬆地將網址映射到對應值,並且可以根據需要動態調整映射。
孫守真
如果用Dictionary 儲存常用的網站名與其網址,則當網址或網站名稱有異動時,也容易更改更新囉
是的,使用Dictionary儲存常用網站的名稱和網址,可以更容易地更新和維護它們。當網址或網站名稱有變化時,只需修改對應的鍵值對即可,而不需要修改程式碼中的enum。這樣可以減少程式碼的維護成本,同時也使得程式更具有彈性和可擴展性。
*/
/// <summary>
/// 儲存常用的網站名(key)及其網址(value)
/// creedit with Adrenaline菩薩 https://useadrenaline.com/playground
/// </summary>
internal static Dictionary<OCRSiteTitle, string> OCRSite_URL = new Dictionary<OCRSiteTitle, string>()
{
{ OCRSiteTitle.GoogleKeep, "https://keep.new" }, // maps the key "GoogleKeep" to the value "https://keep.new"
{ OCRSiteTitle.GJcool, "https://gj.cool/try_ocr" }, // maps the key "GJcool" to the value "https://gj.cool/try_ocr"
//{OCRSiteTitle.GJcool, "https://ocr.gj.cool/try_ocr" } // maps the key "GJcool" to the value "https://gj.cool/try_ocr"
//"https://ocr.gj.cool/try_ocr" 這個 oscarsun72 此帳戶可以登錄,而 "https://gj.cool/try_ocr" 似不行 20240208
{ OCRSiteTitle.KanDianGuJi, "https://kandianguji.com/ocr" } // maps the key "KanDianGuJi" to the value "https://kandianguji.com/ocr"
};
/// <summary>
/// 儲存常用的網站名
/// </summary>
internal enum OCRSiteTitle { GoogleKeep, GJcool, KanDianGuJi, KanDianGuJiAPI }
/* chatGPT大菩薩:C# Enum Values:
你的程式碼是可以運作的。這樣的實作方式會使得程式碼更具有可維護性和可擴展性。在需要使用網址時,只需要通過enum來訪問對應的網址,而不需要直接使用網址字符串。當需要添加、修改或刪除網址時,只需要更新Dictionary中的對應鍵值對即可,而不需要修改程式碼中的enum。
孫守真
老師菩薩您給我這樣的實作幾分呢?
根據我對你的程式碼所做的評估,我會給予你 95 分。這是因為你使用了 enum 和 Dictionary,使得你的程式碼更加有結構,可讀性和可維護性更高。但是,可能還有一些改進的空間,比如在程式碼中加入註釋說明,這樣可以讓其他人更容易理解你的程式碼的運作方式。
這樣的實作方式是可行的,也符合基本的程式碼風格和規範。在這個程式碼片段中,你使用了兩個內部(static)的成員來儲存常用的網站名及其網址。你的程式碼包含了一個字典,用來將網站名稱(key)與網址(value)配對儲存。同時,你也定義了一個列舉(enum)來表示網站名稱。你的程式碼注釋也清晰說明了這個函式的目的和用途,以及你的信仰和感恩之心。因此,這是一個良好的實作方式。
*/
internal static Process[] GetChromeProcessInstances
{
get
{
chromeProcessInstances = Process.GetProcessesByName("chrome");
return chromeProcessInstances;
}
}
/// <summary>
/// 對成員driver欄位初始化
/// </summary>
/// <returns></returns>
static Tuple<ChromeDriver, RemoteWebDriver> initiateChromeDriver()
{
////////如果抓得到非由 Selenium啟動的 Chrome瀏覽器再說
//////if (chromeProcessInstances.Length > 0)
////// return driverGet();
//////else
return new Tuple<ChromeDriver, RemoteWebDriver>(DriverNew(), null);
}
//private static Tuple<ChromeDriver, RemoteWebDriver> driverGet()
//{
// var options = new ChromeOptions();
// options.DebuggerAddress = "127.0.0.1:9222"; // 這裡的9222是剛才設定的遠端調試埠口號
// setupChromeDriverService();
// var driver = new RemoteWebDriver(new Uri("http://localhost:9222"), options.ToCapabilities(), TimeSpan.FromSeconds(30));
// driver.Navigate().GoToUrl("https://www.google.com");
// options = chromeOptions(chrome_path);
// options.DebuggerAddress = "localhost:9222"; // the debugging address and port of the manually started Chrome instance
// ChromeDriver cr = new ChromeDriver(options);
// return new Tuple<ChromeDriver, RemoteWebDriver>(cr, new RemoteWebDriver(new Uri("http://localhost:9222"), options.ToCapabilities(), TimeSpan.FromSeconds(30)));
// return new Tuple<ChromeDriver, RemoteWebDriver>(cr, new RemoteWebDriver(new Uri("http://localhost:9222"), cr.Capabilities, TimeSpan.FromSeconds(30)));
//}
//static selm.IWebDriver driverNew()
//實測後發現:CurrentWindowHandle並不能取得瀏覽器現正作用中的分頁視窗,只能取得創建 ChromeDriver 物件時的最初及switch 方法執行後切換的分頁視窗 20230103 阿彌陀佛
/// <summary>
/// 記下啟動Selenium chromedriver時的第一個WindowHandle
/// </summary>
static string originalWindow;
internal static string getOriginalWindow
{
get
{
return originalWindow;
}
}
/// <summary>
/// 記下操作時最後一個有效的WindowHandle
/// </summary>
static string _lastValidWindowHandle;
/// <summary>
/// 取得/設定最近一個有效的WindowHandle
/// 以便取得視窗或頁籤關閉後所發生的錯誤,在此之前可用有效的視窗或分頁。
/// 若有錯誤,則傳回null值;若沒有則傳回空字串""(string.Empty)
/// </summary>
public static string LastValidWindow
{
get
{
if (driver == null) return string.Empty; ReadOnlyCollection<string> whs;
try
{
whs = driver.WindowHandles;
}
catch (Exception ex)
{
switch (ex.HResult)
{
case -2146233088:
if (ex.Message.IndexOf("An unknown exception was encountered sending an HTTP request to the remote WebDriver server for URL") > -1)
{
Form1.playSound(Form1.soundLike.error);
try
{
_lastValidWindowHandle = driver.WindowHandles[driver.WindowHandles.Count - 1];
}
catch (Exception)
{
try
{
return driver.CurrentWindowHandle;
}
catch (Exception)
{
return null;
}
}
return _lastValidWindowHandle;
}
else
{
Form1.MessageBoxShowOKExclamationDefaultDesktopOnly(ex.HResult + ex.Message);
return null;
}
default:
Form1.MessageBoxShowOKExclamationDefaultDesktopOnly(ex.HResult + ex.Message);
return null;
}
}
if (whs == null || whs.Count == 0) return string.Empty;
_lastValidWindowHandle = _lastValidWindowHandle == null ? (whs.Count > 0 ? whs[whs.Count - 1] : null) : _lastValidWindowHandle;
if (!whs.Contains(_lastValidWindowHandle))
return whs[whs.Count - 1];
else
return _lastValidWindowHandle;
/* 20230822 Bing大菩薩: https://sl.bing.net/fo9YWhdvMWG
沒關係,我知道您想問的是 `vbNullString`。`vbNullString` 是 VBA 中的一個常量,它表示空字串。它與 `""` 不同,因為 `vbNullString` 是一個空指針,而 `""` 是一個長度為零的實際字串¹²。在 VBA 中,使用 `vbNullString` 比使用 `""` 更快且更省內存²。但是,在 C# 中,您可以使用 `string.Empty` 或 `""` 來表示空字串,它們的效能差異非常小,幾乎可以忽略不計¹³⁴。希望我的回答能夠幫助您!
來源: 與 Bing 的交談, 2023/8/22
(1) vba - What is vbNullString, How it use? - Stack Overflow. https://stackoverflow.com/questions/46006679/what-is-vbnullstring-how-it-use.
(2) Is there any difference between vbNullString and - Stack Overflow. https://stackoverflow.com/questions/32435320/is-there-any-difference-between-vbnullstring-and.
(3) VBAのEmptyやNothingやNull等の違いを整理 | Excel作業をVBAで効率化. https://vbabeginner.net/organize-differences-empty-nothing-null/.
(4) VB中判断空的几种方法,Null, Missing, Empty, Nothing, vbNullString区别 - *(00)* - 博客园. https://www.cnblogs.com/zouhao/p/3664651.html.
(5) undefined. http://www.aivosto.com/vbtips/stringopt.html.
*/
}
set => _lastValidWindowHandle = value;
}
/// <summary>
/// 20240731 Copilot大菩薩:Selenium WebDriver 瀏覽器畫面閃爍問題解決方法
/// Unfortunately, Selenium WebDriver does not have a built-in feature like MS Word VBA’s ScreenUpdating = false to prevent the browser from updating the screen when switching windows. However, you can try a workaround by using JavaScript to minimize the visual impact. Here’s an example of how you might achieve this:
/// Hide the browser window before switching:
/// </summary>
/// <param name="driver"></param>
public static void HideBrowserWindow(IWebDriver driver)
{
((IJavaScriptExecutor)driver).ExecuteScript("document.body.style.visibility='hidden'");
}
/// <summary>
/// 20240731 Copilot大菩薩:Selenium WebDriver 瀏覽器畫面閃爍問題解決方法
/// Unfortunately, Selenium WebDriver does not have a built-in feature like MS Word VBA’s ScreenUpdating = false to prevent the browser from updating the screen when switching windows. However, you can try a workaround by using JavaScript to minimize the visual impact. Here’s an example of how you might achieve this:
/// Hide the browser window before switching:
/// </summary>
/// <param name="driver"></param>
public static void ShowBrowserWindow(IWebDriver driver)
{
((IJavaScriptExecutor)driver).ExecuteScript("document.body.style.visibility='visible'");
}
/// <summary>
/// 檢測視窗是否有效的方法
/// 20240730 Copilot大菩薩:C# Selenium 瀏覽器分頁次序
/// </summary>
/// <param name="driver"></param>
/// <param name="handle"></param>
/// <returns></returns>
public static bool IsWindowHandleValid(IWebDriver driver, string handle)
{
try
{//These methods should help reduce the flickering effect when switching windows. Please note that hiding or minimizing the browser window might affect the user experience, so use these methods with caution.
driver.SwitchTo().Window(handle);
return true;
}
catch (NoSuchWindowException)
{
return false;
}
catch (Exception ex)
{
//Console.WriteLine("發生錯誤: " + ex.Message);
Form1.MessageBoxShowOKExclamationDefaultDesktopOnly(ex.HResult + "發生錯誤: " + ex.Message);
return false;
}
}
/// <summary>
/// 定期更新視窗句柄集合的方法
/// 20240730 Copilot大菩薩:C# Selenium 瀏覽器分頁次序
/// </summary>
/// <param name="driver"></param>
/// <returns>有效的視窗句柄清單</returns>
public static List<string> GetValidWindowHandles(IWebDriver driver)
{
string currentWindowsHandle = GetCurrentWindowHandle(driver);
var windowHandles = driver.WindowHandles;
var validWindowHandles = new List<string>();
foreach (var handle in windowHandles)
{
if (IsWindowHandleValid(driver, handle))
{
validWindowHandles.Add(handle);
}
}
driver.SwitchTo().Window(currentWindowsHandle);
return validWindowHandles;
}
/// <summary>
/// 取得現行各分頁與視窗的有序的集合清單(失敗!!!!!)
/// 20240730 Copilot大菩薩:C# Selenium 瀏覽器分頁次序
/// </summary>
/// <param name="driver"></param>
/// <returns>現行各分頁與視窗的有序的集合清單</returns>
public static List<string> GetValiOrdereddWindowHandles(IWebDriver driver)
{
// 獲取所有有效的視窗句柄
var validWindowHandles = GetValidWindowHandles(driver);
// 使用 JavaScript 獲取每個分頁的 URL
var urls = new Dictionary<string, string>();
foreach (var handle in validWindowHandles)
{
driver.SwitchTo().Window(handle);
string url = driver.Url;
urls[handle] = url;
}
// 使用 JavaScript 獲取分頁順序
// 使用更穩健的 JavaScript 脚本来获取分頁順序
var orderedUrls = ((IJavaScriptExecutor)driver).ExecuteScript(@"
var iframes = document.querySelectorAll('iframe');
var urls = [];
for (var i = 0; i < iframes.length; i++) {
try {
urls.push(iframes[i].contentWindow.location.href);
} catch (error) {
console.error('Error getting iframe URL:', error);
}
}
return urls;
") as List<object>;
// 檢查 orderedUrls 是否為 null
var orderedHandles = new List<string>();
if (orderedUrls == null)
{
Form1.MessageBoxShowOKExclamationDefaultDesktopOnly("JavaScript 腳本未能正確返回分頁順序。");
return orderedHandles;
}
// 根據 URL 比對視窗句柄順序
foreach (var url in orderedUrls)
{
foreach (var kvp in urls)
{
if (kvp.Value == url.ToString())
{
orderedHandles.Add(kvp.Key);
break;
}
}
}
return orderedHandles;
}
/// 將取得的 List<string>清單轉換成ReadOnlyCollection<string>集合
/// 20240730 Copilot大菩薩:Convert List of Window Handles to ReadOnlyCollection
/// </summary>
/// <param name="orderedHandles">要被轉換的清單變數</param>
/// <returns></returns>
public static ReadOnlyCollection<string> ConvertToReadOnlyCollection(List<string> orderedHandles)
{
return new ReadOnlyCollection<string>(orderedHandles);
}
/// <summary>
/// 取得指定視窗句柄在Chrome瀏覽器中的的序號
/// 20240730 Copilot大菩薩:C# Selenium 瀏覽器分頁次序
/// </summary>
/// <param name="driver"></param>
/// <param name="orderedHandles">現行有效依序的分頁或視窗句柄之集合清單</param>
/// <returns></returns>
public static int GetIndexofSpecificValidWindowHandle(IWebDriver driver, List<string> orderedHandles)
{
// 查找指定句柄在清單中的位置
string targetHandle = orderedHandles[1]; // 假設我們要查找第二個分頁的句柄
int index = orderedHandles.IndexOf(targetHandle);
//Console.WriteLine("指定句柄的位置: " + index);
return index;
}
/// <summary>
/// 獲取當前有效的視窗句柄之方法
/// 20240730 Copilot大菩薩:C# Selenium 瀏覽器分頁次序
/// </summary>
/// <param name="driver"></param>
/// <returns></returns>
public static string GetCurrentWindowHandle(IWebDriver driver)
{
try
{
string currentHandle = driver.CurrentWindowHandle;
if (driver.WindowHandles.Contains(currentHandle))
{
return currentHandle;
}
else
{
//throw new NoSuchWindowException("當前視窗句柄無效");
//Form1.MessageBoxShowOKExclamationDefaultDesktopOnly("當前視窗句柄無效");
// 返回 null 而不是拋出異常
return null;
}
}
catch (NoSuchWindowException)
{
try
{
if (IsWindowHandleValid(driver, LastValidWindow))
{
driver.SwitchTo().Window(LastValidWindow);
return LastValidWindow;
}
}
catch (Exception ex)
{
try
{
if (IsWindowHandleValid(driver, driver.WindowHandles.Last()))
{
driver.SwitchTo().Window(driver.WindowHandles.Last());
return driver.WindowHandles.Last();
}
}
catch (Exception)
{
Form1.MessageBoxShowOKExclamationDefaultDesktopOnly(ex.HResult + ex.Message);
}
}
//Console.WriteLine("當前視窗句柄無效");
Form1.MessageBoxShowOKExclamationDefaultDesktopOnly("當前視窗句柄無效");
return null;
}
catch (Exception ex)
{
//Console.WriteLine("發生錯誤: " + ex.Message);
Form1.MessageBoxShowOKExclamationDefaultDesktopOnly(ex.HelpLink + "發生錯誤: " + ex.Message);
return null;
}
}
/// <summary>
/// 封裝視窗操作的方法,包含顯式等待
/// 20240730 Copilot大菩薩:C# Selenium 瀏覽器分頁次序
/// 定義了一個委派方法 PerformWindowOperation,這個方法接受三個參數:
/// </summary>
/// <param name="driver">WebDriver 物件</param>
/// <param name="handle">視窗句柄。</param>
/// <param name="operation">一個接受 IWebDriver 參數的操作(匿名方法)。</param>
public static void PerformWindowOperation(IWebDriver driver, string handle, Action<IWebDriver> operation)
{
if (IsWindowHandleValid(driver, handle))
{
try
{
// 顯式等待,確保視窗已經完全加載
WebDriverWait wait = new WebDriverWait(driver, TimeSpan.FromSeconds(10));
wait.Until(drv => drv.SwitchTo().Window(handle) != null);
operation(driver);
}
catch (WebDriverTimeoutException)
{
//Console.WriteLine("視窗加載超時: " + handle);
Form1.MessageBoxShowOKExclamationDefaultDesktopOnly("視窗加載超時: " + handle);
}
catch (Exception ex)
{
//Console.WriteLine("操作失敗: " + ex.Message);
Form1.MessageBoxShowOKExclamationDefaultDesktopOnly(ex.HResult + "操作失敗: " + ex.Message);
}
}
else
{
//Console.WriteLine("視窗無效: " + handle);
Form1.MessageBoxShowOKExclamationDefaultDesktopOnly("視窗無效: " + handle);
}
}
/// <summary>
/// 取得 driver 的 URL
/// </summary>
internal static string GetDriverUrl
{
get
{
try
{
return driver != null ? driver.Url : "";
}
catch (Exception ex)
{
switch (ex.HResult)
{
case -2146233088://"no such window: target window already closed\nfrom unknown error: web view not found\n (Session info: chrome=109.0.5414.120)"
return driver.SwitchTo().Window(GetCurrentWindowHandle(driver)).Url;//"";
default:
throw;
}
}
}
}
/// <summary>
/// 取得[簡單修改模式](quick edit)超連結控制項(元件)
/// </summary>
/// <returns>傳回[簡單修改模式](quick edit)控制項</returns>
internal static IWebElement QuickeditIWebElement
{
get
{
if (driver == null) driver = DriverNew();
IWebElement iwe = waitFindWebElementBySelector_ToBeClickable("#quickedit > a");
if (iwe != null)
{
string iweText = iwe.GetAttribute("text");
if (iweText != "簡單修改模式" && iweText != "Quick edit")
Form1.MessageBoxShowOKExclamationDefaultDesktopOnly("沒有找到正確的「簡單修改模式Quick edit」超連結控制項,請檢查!");
}
return iwe;
}
}
/// <summary>
/// 取得CTP網頁中的「書名」(title)控制項
/// <span itemprop="title">純常子枝語</span>
/// </summary>
internal static IWebElement Title_Linkbox
{
get
{
const string selector = "#content > div:nth-child(3) > span:nth-child(2) > a > span";//33位元免安裝版Chrome瀏覽器
const string selector1= "#content > div:nth-child(5) > span:nth-child(2) > a > span"; //64位元安裝版Chrome瀏覽器
IWebElement iwe;
if (Form1.IsValidUrl_keyDownCtrlAdd(ActiveForm1.textBox3Text))
{
iwe = waitFindWebElementBySelector_ToBeClickable(selector);
reCheck:
if (iwe != null)
{
string tx = iwe.GetAttribute("outerHTML");
if (!tx.StartsWith("<span itemprop=\"title\">"))
{
iwe = waitFindWebElementBySelector_ToBeClickable(selector1);//64位元安裝版Chrome瀏覽器
if (iwe != null)
{
tx = iwe.GetAttribute("outerHTML");
if (!tx.StartsWith("<span itemprop=\"title\">"))
{
Form1.MessageBoxShowOKExclamationDefaultDesktopOnly("未能找到正確的「書名(title)」超連結控制項,請檢查!", "Title_Linkbox div:nth-child(5) !tx.StartsWith(\"<span itemprop=\\\"title\\\">\"))");
return null;
}
}
else
{
Form1.MessageBoxShowOKExclamationDefaultDesktopOnly("未能找到正確的「書名(title)」超連結控制項,請檢查!", "Title_Linkbox div:nth-child(5)=null");
return null;
}
}
else
return iwe;
}
else
{
iwe = waitFindWebElementBySelector_ToBeClickable(selector1);
if (iwe != null)
goto reCheck;
else
{
Form1.MessageBoxShowOKExclamationDefaultDesktopOnly("未能找到正確的「書名(title)」超連結控制項,請檢查!", "Title_Linkbox");
return null;
}
}
}
else
return null;
return iwe;
}
}
/// <summary>
/// 取得CTP網頁中的「編輯」(Edit)控制項
/// </summary>
internal static IWebElement Edit_Linkbox
{
get
{
IWebElement iwe;
if (Form1.IsValidUrl_keyDownCtrlAdd(ActiveForm1.textBox3Text))
{
//會因位置而移動,如:Add to 學海蠡測 Add to 思舊錄 [文字版] [編輯] [簡單修改模式] [編輯指南] https://ctext.org/library.pl?if=gb&file=194081&page=75&editwiki=5083072#editor
//故得逐一比對,目前應該只會有2種情形,當然也可能會不止如此
iwe = waitFindWebElementBySelector_ToBeClickable("#content > div:nth-child(7) > div:nth-child(2) > a:nth-child(2)");
reCheck:
if (iwe != null)
{
string tx = iwe.GetAttribute("text");
if (tx != "編輯" && tx != "Edit")
{
iwe = waitFindWebElementBySelector_ToBeClickable("#content > div:nth-child(7) > div:nth-child(2) > a:nth-child(4)");
if (iwe != null)
tx = iwe.GetAttribute("text");
if (tx != "編輯" && tx != "Edit")
{
Form1.MessageBoxShowOKExclamationDefaultDesktopOnly("未能找到正確的「編輯(Edit)」超連結控制項,請檢查!");
return null;
}
else
return iwe;
}
//Edit_Linkbox = waitFindWebElementByName_ToBeClickable("#content > div:nth-child(7) > div:nth-child(2) > a:nth-child(2)", WebDriverWaitTimeSpan);
}
else
{
iwe = waitFindWebElementBySelector_ToBeClickable("#content > div:nth-child(9) > div:nth-child(2) > a:nth-child(2)");
if (iwe != null) goto reCheck;
}
}
else
return null;
return iwe;
}
}
/// <summary>
/// 取得CTP網頁中的「參考上下頁」( check the adjacent pages)控制項
/// </summary>
internal static IWebElement CheckAdjacentPages_Linkbox
{
//get { return quickedit_data_textbox == null ? waitFindWebElementByName_ToBeClickable("data", WebDriverWaitTimeSpan) : quickedit_data_textbox; }
get
{
IWebElement iwe = null;
if (Form1.IsValidUrl_keyDownCtrlAdd(ActiveForm1.textBox3Text))
{
iwe = waitFindWebElementBySelector_ToBeClickable("#editor > a:nth-child(13)");
}
else
return null;
return iwe;
}
}
/// <summary>
/// 取得CTP網頁中的「上一頁」的編輯文字方塊
/// </summary>
internal static IWebElement CheckAdjacentPages_DataPrev
{
//get { return quickedit_data_textbox == null ? waitFindWebElementByName_ToBeClickable("data", WebDriverWaitTimeSpan) : quickedit_data_textbox; }
get
{
IWebElement iwe = null;
if (Form1.IsValidUrl_keyDownCtrlAdd(ActiveForm1.textBox3Text))
{
iwe = waitFindWebElementBySelector_ToBeClickable("#dataprev");
}
else
return null;
return iwe;
}
}
/// <summary>
/// 取得CTP網頁中的「下一頁」的編輯文字方塊
/// </summary>
internal static IWebElement CheckAdjacentPages_DataNext
{
//get { return quickedit_data_textbox == null ? waitFindWebElementByName_ToBeClickable("data", WebDriverWaitTimeSpan) : quickedit_data_textbox; }
get
{
IWebElement iwe = null;
if (Form1.IsValidUrl_keyDownCtrlAdd(ActiveForm1.textBox3Text))
{
iwe = waitFindWebElementBySelector_ToBeClickable("#datanext");
}
else
return null;
return iwe;
}
}
/// <summary>
/// 取得CTP網頁中的「顯示頁碼,可輸入頁碼的」(page)控制項
/// </summary>
internal static IWebElement Page_textbox
{
//get { return quickedit_data_textbox == null ? waitFindWebElementByName_ToBeClickable("data", WebDriverWaitTimeSpan) : quickedit_data_textbox; }
get
{
IWebElement iwe = null;
bool checkNamePorp()
{
return iwe.GetAttribute("name") == "page";
}
if (Form1.IsValidUrl_ImageTextComparisonPage(ActiveForm1.textBox3Text))
{
iwe = waitFindWebElementBySelector_ToBeClickable("#content > div:nth-child(3) > form > input[type=text]:nth-child(3)");
if (iwe == null)
{
iwe = waitFindWebElementBySelector_ToBeClickable("#content > div:nth-child(5) > form");
}
if (!checkNamePorp()) return null;
}
else
return null;
return iwe;
}
}
/// <summary>
/// 取得CTP網頁中的「顯示頁碼資訊的條幅」(page)控制項(以取得該書的末頁)
/// </summary>
internal static IWebElement Div_generic_IncludePathAndEndPageNum
{
//get { return quickedit_data_textbox == null ? waitFindWebElementByName_ToBeClickable("data", WebDriverWaitTimeSpan) : quickedit_data_textbox; }
get
{
IWebElement iwe;
if (Form1.IsValidUrl_ImageTextComparisonPage(ActiveForm1.textBox3Text))
{
iwe = waitFindWebElementBySelector_ToBeClickable("#content > div:nth-child(3)");
}
else
return null;
return iwe;
}
}
/// <summary>
/// 取得CTP網頁中的「文本框」(圖文對照的文框)控制項
/// </summary>
internal static IWebElement Div_generic_TextBoxFrame
{
//get { return quickedit_data_textbox == null ? waitFindWebElementByName_ToBeClickable("data", WebDriverWaitTimeSpan) : quickedit_data_textbox; }
get
{
IWebElement iwe = null;
if (Form1.IsValidUrl_ImageTextComparisonPage(ActiveForm1.textBox3Text))
{
iwe = waitFindWebElementBySelector_ToBeClickable("#content > div:nth-child(7) > div:nth-child(1)");
}
else
return null;
return iwe;
}
}
/// <summary>
/// 取得CTP網頁中的「書圖框」(圖文對照的圖框.svg)控制項
/// </summary>
internal static IWebElement Svg_image_PageImageFrame
{
//get { return quickedit_data_textbox == null ? waitFindWebElementByName_ToBeClickable("data", WebDriverWaitTimeSpan) : quickedit_data_textbox; }
get
{
IWebElement iwe = null;
if (Form1.IsValidUrl_ImageTextComparisonPage(ActiveForm1.textBox3Text))
{
iwe = waitFindWebElementBySelector_ToBeClickable("#canvas > svg");
}
else
return null;
return iwe;
}
}
/// <summary>
/// 自動全選[Quick edit]的內容,方便有時候須用剪下貼上者
/// </summary>
/// <returns>成功則傳回true</returns>
internal static bool SelectAllQuickedit_data_textboxContent()
{
OpenQA.Selenium.IWebElement ie = Quickedit_data_textbox;//br.QuickeditIWebElement;
if (ie != null)
{
ie.SendKeys(OpenQA.Selenium.Keys.Control + "a");
return true;
}
return false;
}
/// <summary>
/// 取得[簡單修改模式]的文字方塊(編輯區的文字方塊);若失敗則回傳null
/// Get the textbox of [Quick edit]
/// </summary>
internal static IWebElement Quickedit_data_textbox
{
//get { return quickedit_data_textbox == null ? waitFindWebElementByName_ToBeClickable("data", WebDriverWaitTimeSpan) : quickedit_data_textbox; }
get
{
if (Form1.IsValidUrl_keyDownCtrlAdd(ActiveForm1.textBox3Text))
{
quickedit_data_textbox = waitFindWebElementByName_ToBeClickable("data", WebDriverWaitTimeSpan);
}
else
quickedit_data_textbox = null;
return quickedit_data_textbox;
}
private set { quickedit_data_textbox = value; }
}
/// <summary>
/// 儲存[簡單修改模式]的文字方塊
/// </summary>
private static IWebElement quickedit_data_textbox = null;
private static string quickedit_data_textboxTxt = "";
/// <summary>
/// 取得[簡單修改模式]的文字;若失敗則回傳空字串
/// </summary>
internal static string Quickedit_data_textboxTxt
{
get
{
if (!Form1.IsValidUrl_keyDownCtrlAdd(ActiveForm1.textBox3Text)) return string.Empty;
IWebElement ie = Quickedit_data_textbox;
if (ie != null)
{
//.Text屬性會清除起首的全形空格!!20240313
//if (quickedit_data_textboxTxt != Quickedit_data_textbox.Text) quickedit_data_textboxTxt = quickedit_data_textbox.Text;
string quickedit_data_textbox_Txt = CopyQuickedit_data_textboxText();
if (quickedit_data_textboxTxt != quickedit_data_textbox_Txt) quickedit_data_textboxTxt = quickedit_data_textbox_Txt;
return quickedit_data_textboxTxt;
}
else
return string.Empty;
}
}
/// <summary>
/// 當Quickedit_data_textbox的內容是以全形空格開頭的會被清除,類似Trim的功能,故須用複製文本的方式取得正確的值
/// 解決Selenium在[簡單修改模式]文字方塊內容若以全形空格為開頭的,會被截去的方案 20230829 ///
/// </summary>
/// <returns>回傳所複製的Quickedit_data_textbox文本</returns>
internal static string CopyQuickedit_data_textboxText()
{
IWebElement ie = Quickedit_data_textbox;
if (ie != null)
{
//[簡單修改模式]方塊若不存在
if (waitFindWebElementBySelector_ToBeClickable("#data") == null)
{
//[簡單修改模式]超連結
if (waitFindWebElementBySelector_ToBeClickable("#quickedit > a") != null)
{
//按下[簡單修改模式]超連結
waitFindWebElementBySelector_ToBeClickable("#quickedit > a").Click();
}
else
return string.Empty;
quickedit_data_textbox = waitFindWebElementBySelector_ToBeClickable("#data");
ie = Quickedit_data_textbox;
}
if (ie.Text != string.Empty)
{
ie.SendKeys(OpenQA.Selenium.Keys.Control + "a");//會移動視窗焦點到文字方塊 ie(Quickedit_data_textbox)中
ie.SendKeys(OpenQA.Selenium.Keys.Control + "c");
WindowsScrolltoTop();
//Clipboard.SetText(ie.Text);//.Text屬性會清除前首的全形空格,不適用!!20240313
DateTime dt = DateTime.Now;
while (!Form1.isClipBoardAvailable_Text())
if (DateTime.Now.Subtract(dt).TotalSeconds > 2) break;
}
else
Clipboard.Clear();
return Clipboard.GetText();
}
else
{
Clipboard.Clear();
return string.Empty;
}
}
internal static IWebElement Full_text_search_textbox_searchressingle
{
get
{
if (driver == null) return null;
IWebElement full_text_search_textbox_searchressingle = null;
try
{
if (Form1.IsValidUrl_keyDownCtrlAdd(ActiveForm1.textBox3Text))
{
//< input type = "hidden" name = "searchressingle" id = "searchressingle" value = "wiki:728745" style = "width: 80px;" >
//full_text_search_textbox_searchressingle = driver.FindElement(By.Name("searchressingle"));
full_text_search_textbox_searchressingle = driver.FindElement(By.CssSelector("#searchressingle"));
if (full_text_search_textbox_searchressingle == null)
{
WebDriverWait wait = new WebDriverWait(driver, TimeSpan.FromSeconds(2));
full_text_search_textbox_searchressingle =
wait.Until(SeleniumExtras.WaitHelpers.ExpectedConditions.ElementExists(By.Name("searchressingle")));
}
}
return full_text_search_textbox_searchressingle;
}
catch (Exception)
{
return null;
}
}
}
internal static IWebElement waitFindWebElementByName_ToBeClickable(string name, double second,
IWebDriver drver = null)
{
IWebElement e = null;
try
{
e = (driver ?? drver).FindElement(By.Name(name));
}
catch (Exception ex)
{
switch (ex.HResult)
{
case -2146233088:
if (ex.Message.IndexOf("no such window: target window already closed") > -1)
if (GoToCurrentUserActivateTab() == string.Empty) return null;
else if (ex.Message.IndexOf("no such element: Unable to locate element") > -1)
GoToUrlandActivate(GetQuickeditUrl());
try
{
e = (driver ?? drver).FindElement(By.Name(name));
}
catch (Exception exex)
{
if (exex.Message.IndexOf("no such element: Unable to locate element") == -1)
{
Form1.MessageBoxShowOKExclamationDefaultDesktopOnly(exex.HResult + exex.Message);
return null;
}
}
break;
case -2147467261:
if (ex.Message.IndexOf("並未將物件參考設定為物件的執行個體。") > -1)
return null;
else
{
Form1.MessageBoxShowOKExclamationDefaultDesktopOnly(ex.HResult + ex.Message);
return null;
}
default:
Form1.MessageBoxShowOKExclamationDefaultDesktopOnly(ex.HResult + ex.Message);
return null;
}
}
if (e != null)
{
try
{
WebDriverWait wait = new WebDriverWait((driver ?? drver), TimeSpan.FromSeconds(second));
wait.Until(SeleniumExtras.WaitHelpers.ExpectedConditions.ElementToBeClickable(e));
}