tarzi 0.2.3

Rust-native lite search for AI applications
Documentation
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
use std::time::Duration;
use tarzi::constants::CHROMEDRIVER_DEFAULT_URL;
use tarzi::search::parser::{
    BaiduParser, BaseParser, BingParser, BraveParser, DuckDuckGoParser, GoogleParser,
    SogouWeixinParser,
};
use tarzi::search::types::SearchEngineType;
use tarzi::utils::is_webdriver_available;
use thirtyfour::{By, DesiredCapabilities, Key, WebDriver};

/// Integration tests for search parsers
/// These tests require internet access and a running WebDriver server
/// Perform a real Bing search using WebDriver and return the HTML
async fn perform_bing_search(query: &str) -> Result<String, Box<dyn std::error::Error>> {
    let webdriver_url = CHROMEDRIVER_DEFAULT_URL;

    // Setup Firefox capabilities for geckodriver (default)
    let mut caps = DesiredCapabilities::firefox();
    caps.add_arg("--disable-blink-features=AutomationControlled")?;
    caps.add_arg("--disable-web-security")?;
    caps.add_arg("--disable-features=VizDisplayCompositor")?;

    // Connect to WebDriver
    let driver = WebDriver::new(webdriver_url, caps).await?;

    let result = async {
        // Navigate to Bing
        driver.goto("https://www.bing.com").await?;
        println!("Navigated to Bing homepage");

        // Wait a moment for the page to load
        tokio::time::sleep(Duration::from_millis(1000)).await;

        // Find search box and enter query
        let search_box = driver.find(By::Name("q")).await?;
        search_box.clear().await?;
        search_box.send_keys(query).await?;
        search_box.send_keys(Key::Enter).await?;
        println!("Submitted search query: '{query}'");

        // Wait for search results to load
        let mut search_results_loaded = false;
        for _ in 0..20 {
            tokio::time::sleep(Duration::from_millis(500)).await;
            match driver.find_all(By::Css("li.b_algo")).await {
                Ok(elements) if !elements.is_empty() => {
                    println!("Search results loaded successfully");
                    search_results_loaded = true;
                    break;
                }
                _ => continue,
            }
        }

        if !search_results_loaded {
            println!("Warning: Search results did not load within timeout, trying to get page source anyway");
        }

        // Additional wait to ensure all results are loaded
        tokio::time::sleep(Duration::from_millis(2000)).await;

        // Get page source
        let page_source = driver.source().await?;
        println!("Retrieved page source, length: {} characters", page_source.len());

        Ok::<String, Box<dyn std::error::Error>>(page_source)
    }.await;

    // Always quit the driver
    if let Err(e) = driver.quit().await {
        eprintln!("Warning: Failed to quit WebDriver: {e}");
    }

    result
}

/// Perform a real DuckDuckGo search using WebDriver and return the HTML
async fn perform_duckduckgo_search(query: &str) -> Result<String, Box<dyn std::error::Error>> {
    let webdriver_url = CHROMEDRIVER_DEFAULT_URL;

    // Setup Firefox capabilities for geckodriver (default)
    let mut caps = DesiredCapabilities::firefox();
    caps.add_arg("--disable-blink-features=AutomationControlled")?;
    caps.add_arg("--disable-web-security")?;
    caps.add_arg("--disable-features=VizDisplayCompositor")?;
    caps.add_arg("--user-agent=Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36")?;
    caps.add_arg("--no-first-run")?;
    caps.add_arg("--disable-default-apps")?;

    // Connect to WebDriver
    let driver = WebDriver::new(webdriver_url, caps).await?;

    let result = async {
        // Navigate to DuckDuckGo
        driver.goto("https://duckduckgo.com/").await?;
        println!("Navigated to DuckDuckGo homepage");

        // Wait a moment for the page to load
        tokio::time::sleep(Duration::from_millis(2000)).await;

        // Try to find search box with different selectors
        let search_box = match driver.find(By::Id("search_form_input_homepage")).await {
            Ok(element) => element,
            Err(_) => {
                // Try alternative selector
                match driver.find(By::Name("q")).await {
                    Ok(element) => element,
                    Err(_) => driver.find(By::Css("input[type='text']")).await?
                }
            }
        };

        search_box.clear().await?;
        search_box.send_keys(query).await?;
        println!("Entered search query: '{query}'");

        // Try to submit with Enter key first (more natural)
        match search_box.send_keys(Key::Enter).await {
            Ok(_) => {
                println!("Submitted search with Enter key");
            }
            Err(_) => {
                // Fallback to clicking search button
                let search_button = match driver.find(By::Id("search_button_homepage")).await {
                    Ok(element) => element,
                    Err(_) => driver.find(By::Css("button[type='submit']")).await?
                };
                search_button.click().await?;
                println!("Clicked search button");
            }
        }

        // Wait for search results to load
        let mut search_results_loaded = false;
        for _ in 0..20 {
            tokio::time::sleep(Duration::from_millis(500)).await;
            match driver.find_all(By::Css("div.result__body")).await {
                Ok(elements) if !elements.is_empty() => {
                    println!("DuckDuckGo search results loaded successfully");
                    search_results_loaded = true;
                    break;
                }
                _ => continue,
            }
        }

        if !search_results_loaded {
            println!("Warning: DuckDuckGo search results did not load within timeout, trying to get page source anyway");
        }

        // Additional wait to ensure all results are loaded
        tokio::time::sleep(Duration::from_millis(2000)).await;

        // Get page source
        let page_source = driver.source().await?;
        println!("Retrieved DuckDuckGo page source, length: {} characters", page_source.len());

        Ok::<String, Box<dyn std::error::Error>>(page_source)
    }.await;

    // Always quit the driver
    if let Err(e) = driver.quit().await {
        eprintln!("Warning: Failed to quit WebDriver: {e}");
    }

    result
}

/// Perform a real Google search using WebDriver and return the HTML
async fn perform_google_search(query: &str) -> Result<String, Box<dyn std::error::Error>> {
    let webdriver_url = CHROMEDRIVER_DEFAULT_URL;

    // Setup Firefox capabilities for geckodriver (default)
    let mut caps = DesiredCapabilities::firefox();
    caps.add_arg("--disable-blink-features=AutomationControlled")?;
    caps.add_arg("--disable-web-security")?;
    caps.add_arg("--disable-features=VizDisplayCompositor")?;
    caps.add_arg("--user-agent=Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36")?;
    caps.add_arg("--no-first-run")?;
    caps.add_arg("--disable-default-apps")?;

    // Connect to WebDriver
    let driver = WebDriver::new(webdriver_url, caps).await?;

    let result = async {
        // Navigate to Google
        driver.goto("https://www.google.com").await?;
        println!("Navigated to Google homepage");

        // Wait a moment for the page to load
        tokio::time::sleep(Duration::from_millis(2000)).await;

        // Try to accept cookies if prompted
        if let Ok(cookie_button) = driver.find(By::Css("button#L2AGLb")).await
            && (cookie_button.click().await).is_ok()
        {
            println!("Accepted Google cookies");
            tokio::time::sleep(Duration::from_millis(1000)).await;
        }

        // Try to find search box with different selectors
        let search_box = match driver.find(By::Name("q")).await {
            Ok(element) => element,
            Err(_) => {
                // Try alternative selector
                match driver.find(By::Css("input[name='q']")).await {
                    Ok(element) => element,
                    Err(_) => driver.find(By::Css("input[type='text']")).await?
                }
            }
        };

        search_box.clear().await?;
        search_box.send_keys(query).await?;
        println!("Entered search query: '{query}'");

        // Submit with Enter key
        search_box.send_keys(Key::Enter).await?;
        println!("Submitted search with Enter key");

        // Wait for search results to load
        let mut search_results_loaded = false;
        for _ in 0..20 {
            tokio::time::sleep(Duration::from_millis(500)).await;
            match driver.find_all(By::Css("div.tF2Cxc")).await {
                Ok(elements) if !elements.is_empty() => {
                    println!("Google search results loaded successfully");
                    search_results_loaded = true;
                    break;
                }
                _ => continue,
            }
        }

        if !search_results_loaded {
            println!("Warning: Google search results did not load within timeout, trying to get page source anyway");
        }

        // Additional wait to ensure all results are loaded
        tokio::time::sleep(Duration::from_millis(2000)).await;

        // Get page source
        let page_source = driver.source().await?;
        println!("Retrieved Google page source, length: {} characters", page_source.len());

        Ok::<String, Box<dyn std::error::Error>>(page_source)
    }.await;

    // Always quit the driver
    if let Err(e) = driver.quit().await {
        eprintln!("Warning: Failed to quit WebDriver: {e}");
    }

    result
}

/// Perform a real Brave search using WebDriver and return the HTML
async fn perform_brave_search(query: &str) -> Result<String, Box<dyn std::error::Error>> {
    let webdriver_url = CHROMEDRIVER_DEFAULT_URL;

    // Setup Firefox capabilities for geckodriver (default)
    let mut caps = DesiredCapabilities::firefox();
    caps.add_arg("--disable-blink-features=AutomationControlled")?;
    caps.add_arg("--disable-web-security")?;
    caps.add_arg("--disable-features=VizDisplayCompositor")?;
    caps.add_arg("--user-agent=Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36")?;
    caps.add_arg("--no-first-run")?;
    caps.add_arg("--disable-default-apps")?;

    // Connect to WebDriver
    let driver = WebDriver::new(webdriver_url, caps).await?;

    let result = async {
        // Navigate to Brave Search
        driver.goto("https://search.brave.com/").await?;
        println!("Navigated to Brave Search homepage");

        // Wait a moment for the page to load
        tokio::time::sleep(Duration::from_millis(2000)).await;

        // Try to find search box with different selectors
        let search_box = match driver.find(By::Css("input[type='search']")).await {
            Ok(element) => element,
            Err(_) => {
                // Try alternative selectors
                match driver.find(By::Name("q")).await {
                    Ok(element) => element,
                    Err(_) => driver.find(By::Css("input[name='q']")).await?
                }
            }
        };

        search_box.clear().await?;
        search_box.send_keys(query).await?;
        println!("Entered search query: '{query}'");

        // Submit with Enter key
        search_box.send_keys(Key::Enter).await?;
        println!("Submitted search with Enter key");

        // Wait for search results to load
        let mut search_results_loaded = false;
        for _ in 0..20 {
            tokio::time::sleep(Duration::from_millis(500)).await;
            match driver.find_all(By::Css(".result-row")).await {
                Ok(elements) if !elements.is_empty() => {
                    println!("Brave search results loaded successfully");
                    search_results_loaded = true;
                    break;
                }
                _ => continue,
            }
        }

        if !search_results_loaded {
            println!("Warning: Brave search results did not load within timeout, trying to get page source anyway");
        }

        // Additional wait to ensure all results are loaded
        tokio::time::sleep(Duration::from_millis(2000)).await;

        // Get page source
        let page_source = driver.source().await?;
        println!("Retrieved Brave page source, length: {} characters", page_source.len());

        Ok::<String, Box<dyn std::error::Error>>(page_source)
    }.await;

    // Always quit the driver
    if let Err(e) = driver.quit().await {
        eprintln!("Warning: Failed to quit WebDriver: {e}");
    }

    result
}

/// Perform a real Baidu search using WebDriver and return the HTML
async fn perform_baidu_search(query: &str) -> Result<String, Box<dyn std::error::Error>> {
    let webdriver_url = CHROMEDRIVER_DEFAULT_URL;

    // Setup Firefox capabilities for geckodriver (default)
    let mut caps = DesiredCapabilities::firefox();
    caps.add_arg("--disable-blink-features=AutomationControlled")?;
    caps.add_arg("--disable-web-security")?;
    caps.add_arg("--disable-features=VizDisplayCompositor")?;
    caps.add_arg("--user-agent=Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36")?;
    caps.add_arg("--no-first-run")?;
    caps.add_arg("--disable-default-apps")?;

    // Connect to WebDriver
    let driver = WebDriver::new(webdriver_url, caps).await?;

    let result = async {
        // Navigate to Baidu
        driver.goto("https://www.baidu.com").await?;
        println!("Navigated to Baidu homepage");

        // Wait a moment for the page to load
        tokio::time::sleep(Duration::from_millis(2000)).await;

        // Try to find search box
        let search_box = driver.find(By::Id("kw")).await?;
        search_box.clear().await?;
        search_box.send_keys(query).await?;
        println!("Entered search query: '{query}'");

        // Submit search
        let submit_button = driver.find(By::Id("su")).await?;
        submit_button.click().await?;
        println!("Clicked search button");

        // Wait for search results to load
        let mut search_results_loaded = false;
        for _ in 0..20 {
            tokio::time::sleep(Duration::from_millis(500)).await;
            match driver.find_all(By::Css("div#content_left")).await {
                Ok(elements) if !elements.is_empty() => {
                    println!("Baidu search results loaded successfully");
                    search_results_loaded = true;
                    break;
                }
                _ => continue,
            }
        }

        if !search_results_loaded {
            println!("Warning: Baidu search results did not load within timeout, trying to get page source anyway");
        }

        // Additional wait to ensure all results are loaded
        tokio::time::sleep(Duration::from_millis(2000)).await;

        // Get page source
        let page_source = driver.source().await?;
        println!("Retrieved Baidu page source, length: {} characters", page_source.len());

        Ok::<String, Box<dyn std::error::Error>>(page_source)
    }.await;

    // Always quit the driver
    if let Err(e) = driver.quit().await {
        eprintln!("Warning: Failed to quit WebDriver: {e}");
    }

    result
}

/// Perform a real Sogou Weixin search using WebDriver and return the HTML
async fn perform_sogou_weixin_search(query: &str) -> Result<String, Box<dyn std::error::Error>> {
    let webdriver_url = CHROMEDRIVER_DEFAULT_URL;

    // Setup Firefox capabilities for geckodriver (default)
    let mut caps = DesiredCapabilities::firefox();
    caps.add_arg("--disable-blink-features=AutomationControlled")?;
    caps.add_arg("--disable-web-security")?;
    caps.add_arg("--disable-features=VizDisplayCompositor")?;
    caps.add_arg("--no-first-run")?;
    caps.add_arg("--disable-default-apps")?;

    // Connect to WebDriver
    let driver = WebDriver::new(webdriver_url, caps).await?;

    let result = async {
        // Navigate to Sogou Weixin
        driver.goto("https://weixin.sogou.com/").await?;
        println!("Navigated to Sogou Weixin homepage");

        // Wait a moment for the page to load
        tokio::time::sleep(Duration::from_millis(2000)).await;

        // Try to find search box
        let search_box = match driver.find(By::Name("query")).await {
            Ok(el) => el,
            Err(_) => match driver.find(By::Css("input[type='text']")).await {
                Ok(el) => el,
                Err(_) => driver.find(By::Css("input#query")).await?,
            },
        };

        search_box.clear().await?;
        search_box.send_keys(query).await?;
        println!("Entered search query: '{query}'");

        // Submit search: try Enter first, fallback to a submit button
        match search_box.send_keys(Key::Enter).await {
            Ok(_) => println!("Submitted search with Enter key"),
            Err(_) => {
                // Try common button selectors
                if let Ok(btn) = driver.find(By::Css("input[type='submit']")).await {
                    btn.click().await?;
                } else if let Ok(btn) = driver.find(By::Css("button[type='submit']")).await {
                    btn.click().await?;
                }
                println!("Clicked search button");
            }
        }

        // Wait for search results to load - look for result containers
        let mut search_results_loaded = false;
        for _ in 0..20 {
            tokio::time::sleep(Duration::from_millis(500)).await;
            // Weixin result pages often have anchors linking to mp.weixin.qq.com
            match driver
                .find_all(By::Css("a[href*='mp.weixin.qq.com'], a[href*='weixin.sogou.com/link']"))
                .await
            {
                Ok(elements) if !elements.is_empty() => {
                    println!("Sogou Weixin search results loaded successfully");
                    search_results_loaded = true;
                    break;
                }
                _ => continue,
            }
        }

        if !search_results_loaded {
            println!("Warning: Sogou Weixin results did not load within timeout, getting page source anyway");
        }

        // Additional wait to ensure all results are loaded
        tokio::time::sleep(Duration::from_millis(2000)).await;

        // Get page source
        let page_source = driver.source().await?;
        println!(
            "Retrieved Sogou Weixin page source, length: {} characters",
            page_source.len()
        );

        Ok::<String, Box<dyn std::error::Error>>(page_source)
    }
    .await;

    // Always quit the driver
    if let Err(e) = driver.quit().await {
        eprintln!("Warning: Failed to quit WebDriver: {e}");
    }

    result
}

#[tokio::test]
async fn test_sogou_weixin_parser_real_world_integration() {
    // Skip test if WebDriver is not available
    if !is_webdriver_available().await {
        println!("Skipping Sogou Weixin real-world integration test: WebDriver not available");
        println!("To run this test, start a WebDriver server (e.g., geckodriver on port 4444)");
        return;
    }

    println!("Starting real-world Sogou Weixin search integration test...");

    // Perform a real search with timeout (Sogou may have anti-bot)
    let search_query = "rust 编程语言";
    let html_content = match tokio::time::timeout(
        Duration::from_secs(30),
        perform_sogou_weixin_search(search_query),
    )
    .await
    {
        Ok(Ok(html)) => html,
        Ok(Err(e)) => {
            println!("⚠️  Sogou Weixin search failed: {e}");
            println!("This is likely due to anti-automation measures or regional restrictions.");
            println!("The SogouWeixinParser logic is tested by parsing below if HTML present.");
            return; // Skip the test gracefully
        }
        Err(_) => {
            println!("⚠️  Sogou Weixin search timed out after 30 seconds");
            println!("This is likely due to anti-automation measures or CAPTCHA.");
            return; // Skip the test gracefully
        }
    };

    // Simple sanity check
    assert!(html_content.contains("weixin.sogou.com") || html_content.contains("mp.weixin.qq.com"));
    assert!(html_content.len() > 2000);
    println!("✓ Successfully retrieved Sogou Weixin search results HTML");

    // Create SogouWeixinParser and parse the results
    let parser = SogouWeixinParser::new();
    assert_eq!(parser.name(), "SogouWeixinParser");
    assert!(parser.supports(&SearchEngineType::SougouWeixin));
    println!("✓ SogouWeixinParser created and validated");

    let limit = 5;
    let results = match parser.parse(&html_content, limit) {
        Ok(results) => results,
        Err(e) => {
            eprintln!("Failed to parse Sogou Weixin HTML: {e}");
            if std::env::var("TARZI_DEBUG").is_ok() {
                std::fs::write("debug_sogou_weixin.html", &html_content).ok();
                println!("Debug HTML saved to debug_sogou_weixin.html");
            }
            panic!("Parser failed: {e}");
        }
    };

    println!("✓ Successfully parsed {} search results", results.len());

    if results.is_empty() {
        println!("⚠️  Warning: No Sogou Weixin results found. Possible anti-bot or layout change.");
        if std::env::var("TARZI_DEBUG").is_ok() {
            std::fs::write("debug_sogou_weixin_no_results.html", &html_content).ok();
            println!("Debug HTML saved to debug_sogou_weixin_no_results.html");
        }
        return; // Don't fail the test hard in flaky environments
    }

    assert!(
        results.len() <= limit,
        "Should not exceed the requested limit"
    );

    for (i, result) in results.iter().enumerate() {
        println!("Result {}: {} - {}", i + 1, result.title, result.url);
        assert_eq!(result.rank, i + 1, "Rank should be sequential");
        assert!(
            result.url.contains("mp.weixin.qq.com"),
            "URL should point to mp.weixin.qq.com: {}",
            result.url
        );
    }

    // Test with different limits
    let small_limit = 2;
    let small_results = parser.parse(&html_content, small_limit).unwrap();
    assert!(small_results.len() <= small_limit);
}

#[tokio::test]
async fn test_bing_parser_real_world_integration() {
    // Skip test if WebDriver is not available
    if !is_webdriver_available().await {
        println!("Skipping real-world integration test: WebDriver not available");
        println!("To run this test, start a WebDriver server (e.g., geckodriver on port 4444)");
        return;
    }

    println!("Starting real-world Bing search integration test...");

    // Perform a real search
    let search_query = "mirasoth";
    let html_content = match perform_bing_search(search_query).await {
        Ok(html) => html,
        Err(e) => {
            eprintln!("Failed to perform Bing search: {e}");
            panic!("Integration test failed: {e}");
        }
    };

    // Verify we got actual Bing HTML
    assert!(html_content.contains("bing.com"));
    assert!(html_content.len() > 10000); // Bing pages are typically quite large
    println!("✓ Successfully retrieved Bing search results HTML");

    // Create BingParser and parse the results
    let parser = BingParser::new();
    assert_eq!(parser.name(), "BingParser");
    assert!(parser.supports(&SearchEngineType::Bing));
    println!("✓ BingParser created and validated");

    // Parse the real HTML
    let limit = 5;
    let results = match parser.parse(&html_content, limit) {
        Ok(results) => results,
        Err(e) => {
            eprintln!("Failed to parse Bing HTML: {e}");
            // Save HTML for debugging if needed
            if std::env::var("TARZI_DEBUG").is_ok() {
                std::fs::write("debug_bing.html", &html_content).ok();
                println!("Debug HTML saved to debug_bing.html");
            }
            panic!("Parser failed: {e}");
        }
    };

    println!("✓ Successfully parsed {} search results", results.len());

    // Validate the parsed results
    assert!(!results.is_empty(), "Should have found some search results");
    assert!(
        results.len() <= limit,
        "Should not exceed the requested limit"
    );

    // Validate each result structure
    for (i, result) in results.iter().enumerate() {
        println!("Result {}: {} - {}", i + 1, result.title, result.url);

        // Basic validation
        assert!(!result.title.is_empty(), "Title should not be empty");
        assert!(!result.url.is_empty(), "URL should not be empty");
        assert_eq!(result.rank, i + 1, "Rank should be sequential");

        // URL validation
        assert!(
            result.url.starts_with("http://") || result.url.starts_with("https://"),
            "URL should be properly formatted: {}",
            result.url
        );

        // Content validation (for "rust programming language" search)
        let lower_title = result.title.to_lowercase();
        let lower_snippet = result.snippet.to_lowercase();
        let contains_rust = lower_title.contains("rust")
            || lower_snippet.contains("rust")
            || lower_title.contains("programming")
            || lower_snippet.contains("programming");

        if !contains_rust {
            println!(
                "Warning: Result {} may not be relevant to search query",
                i + 1
            );
        }
    }

    println!("✓ All results validated successfully");

    // Test with different limits
    let small_limit = 2;
    let small_results = parser.parse(&html_content, small_limit).unwrap();
    assert!(small_results.len() <= small_limit);
    assert!(small_results.len() <= results.len());
    println!("✓ Parser correctly handles different limits");

    // Test with empty HTML
    let empty_results = parser.parse("", 5).unwrap();
    assert!(empty_results.is_empty());
    println!("✓ Parser correctly handles empty HTML");

    println!("🎉 Real-world Bing parser integration test completed successfully!");
}

#[tokio::test]
async fn test_bing_parser_performance() {
    // Skip test if WebDriver is not available
    if !is_webdriver_available().await {
        println!("Skipping performance test: WebDriver not available");
        return;
    }

    println!("Testing BingParser performance...");

    // Get HTML once
    let html = match perform_bing_search("performance test").await {
        Ok(html) => html,
        Err(e) => {
            println!("Skipping performance test: {e}");
            return;
        }
    };

    let parser = BingParser::new();

    // Test parsing performance
    let start_time = std::time::Instant::now();
    let iterations = 10;

    for _ in 0..iterations {
        let _results = parser.parse(&html, 10).unwrap();
    }

    let elapsed = start_time.elapsed();
    let avg_time = elapsed / iterations;

    println!("Average parsing time: {avg_time:?}");
    assert!(
        avg_time < Duration::from_millis(500),
        "Parsing should be reasonably fast"
    );

    println!("✓ Performance test completed");
}

#[tokio::test]
async fn test_duckduckgo_parser_real_world_integration() {
    // Skip test if WebDriver is not available
    if !is_webdriver_available().await {
        println!("Skipping DuckDuckGo real-world integration test: WebDriver not available");
        println!("To run this test, start a WebDriver server (e.g., geckodriver on port 4444)");
        return;
    }

    println!("Starting real-world DuckDuckGo search integration test...");

    // Perform a real search with timeout
    let search_query = "rust programming language";
    let html_content = match tokio::time::timeout(
        Duration::from_secs(30), // Shorter timeout
        perform_duckduckgo_search(search_query),
    )
    .await
    {
        Ok(Ok(html)) => html,
        Ok(Err(e)) => {
            println!("⚠️  DuckDuckGo search failed: {e}");
            println!("This is likely due to DuckDuckGo's anti-automation measures.");
            println!("The DuckDuckGoParser logic is tested separately in unit tests.");
            return; // Skip the test gracefully
        }
        Err(_) => {
            println!("⚠️  DuckDuckGo search timed out after 30 seconds");
            println!("This is likely due to DuckDuckGo's anti-automation measures.");
            println!("The DuckDuckGoParser logic is tested separately in unit tests.");
            return; // Skip the test gracefully
        }
    };

    // Verify we got actual DuckDuckGo HTML
    assert!(html_content.contains("duckduckgo.com") || html_content.contains("DuckDuckGo"));
    assert!(html_content.len() > 5000); // DuckDuckGo pages are typically quite large
    println!("✓ Successfully retrieved DuckDuckGo search results HTML");

    // Create DuckDuckGoParser and parse the results
    let parser = DuckDuckGoParser::new();
    assert_eq!(parser.name(), "DuckDuckGoParser");
    assert!(parser.supports(&SearchEngineType::DuckDuckGo));
    println!("✓ DuckDuckGoParser created and validated");

    // Parse the real HTML
    let limit = 5;
    let results = match parser.parse(&html_content, limit) {
        Ok(results) => results,
        Err(e) => {
            eprintln!("Failed to parse DuckDuckGo HTML: {e}");
            // Save HTML for debugging if needed
            if std::env::var("TARZI_DEBUG").is_ok() {
                std::fs::write("debug_duckduckgo.html", &html_content).ok();
                println!("Debug HTML saved to debug_duckduckgo.html");
            }
            panic!("Parser failed: {e}");
        }
    };

    println!("✓ Successfully parsed {} search results", results.len());

    // Validate the parsed results
    if results.is_empty() {
        println!("⚠️  Warning: No search results found. This could be due to:");
        println!("   - DuckDuckGo blocking automated requests");
        println!("   - Changes in DuckDuckGo's HTML structure");
        println!("   - Geographic restrictions or different page layout");

        // Don't fail the test immediately, but save debug info
        if std::env::var("TARZI_DEBUG").is_ok() {
            std::fs::write("debug_duckduckgo_no_results.html", &html_content).ok();
            println!("Debug HTML saved to debug_duckduckgo_no_results.html");
        }
    } else {
        assert!(
            results.len() <= limit,
            "Should not exceed the requested limit"
        );

        // Validate each result structure
        for (i, result) in results.iter().enumerate() {
            println!("Result {}: {} - {}", i + 1, result.title, result.url);

            // Basic validation
            assert!(!result.title.is_empty(), "Title should not be empty");
            assert_eq!(result.rank, i + 1, "Rank should be sequential");

            // URL validation (DuckDuckGo might have empty URLs for some results)
            if !result.url.is_empty() {
                assert!(
                    result.url.starts_with("http://")
                        || result.url.starts_with("https://")
                        || result.url.starts_with("/"),
                    "URL should be properly formatted or relative: {}",
                    result.url
                );
            }

            // Content validation (for "rust programming language" search)
            let lower_title = result.title.to_lowercase();
            let lower_snippet = result.snippet.to_lowercase();
            let contains_rust = lower_title.contains("rust")
                || lower_snippet.contains("rust")
                || lower_title.contains("programming")
                || lower_snippet.contains("programming");

            if !contains_rust {
                println!(
                    "Warning: Result {} may not be relevant to search query",
                    i + 1
                );
            }
        }

        println!("✓ All results validated successfully");
    }

    // Test with different limits
    let small_limit = 2;
    let small_results = parser.parse(&html_content, small_limit).unwrap();
    assert!(small_results.len() <= small_limit);
    assert!(small_results.len() <= results.len());
    println!("✓ Parser correctly handles different limits");

    // Test with empty HTML
    let empty_results = parser.parse("", 5).unwrap();
    assert!(empty_results.is_empty());
    println!("✓ Parser correctly handles empty HTML");

    println!("🎉 Real-world DuckDuckGo parser integration test completed successfully!");
}

#[tokio::test]
async fn test_google_parser_real_world_integration() {
    // Skip test if WebDriver is not available
    if !is_webdriver_available().await {
        println!("Skipping Google real-world integration test: WebDriver not available");
        println!("To run this test, start a WebDriver server (e.g., geckodriver on port 4444)");
        return;
    }

    println!("Starting real-world Google search integration test...");

    // Perform a real search with timeout
    let search_query = "rust programming language";
    let html_content = match tokio::time::timeout(
        Duration::from_secs(30), // Shorter timeout
        perform_google_search(search_query),
    )
    .await
    {
        Ok(Ok(html)) => html,
        Ok(Err(e)) => {
            println!("⚠️  Google search failed: {e}");
            println!("This is likely due to Google's anti-automation measures or CAPTCHA.");
            println!("The GoogleParser logic is tested separately in unit tests.");
            return; // Skip the test gracefully
        }
        Err(_) => {
            println!("⚠️  Google search timed out after 30 seconds");
            println!("This is likely due to Google's anti-automation measures or CAPTCHA.");
            println!("The GoogleParser logic is tested separately in unit tests.");
            return; // Skip the test gracefully
        }
    };

    // Verify we got actual Google HTML
    assert!(html_content.contains("google.com") || html_content.contains("Google"));
    assert!(html_content.len() > 5000); // Google pages are typically quite large
    println!("✓ Successfully retrieved Google search results HTML");

    // Create GoogleParser and parse the results
    let parser = GoogleParser::new();
    assert_eq!(parser.name(), "GoogleParser");
    assert!(parser.supports(&SearchEngineType::Google));
    println!("✓ GoogleParser created and validated");

    // Parse the real HTML
    let limit = 5;
    let results = match parser.parse(&html_content, limit) {
        Ok(results) => results,
        Err(e) => {
            eprintln!("Failed to parse Google HTML: {e}");
            // Save HTML for debugging if needed
            if std::env::var("TARZI_DEBUG").is_ok() {
                std::fs::write("debug_google.html", &html_content).ok();
                println!("Debug HTML saved to debug_google.html");
            }
            panic!("Parser failed: {e}");
        }
    };

    println!("✓ Successfully parsed {} search results", results.len());

    // Validate the parsed results
    if results.is_empty() {
        println!("⚠️  Warning: No search results found. This could be due to:");
        println!("   - Google blocking automated requests or showing CAPTCHA");
        println!("   - Changes in Google's HTML structure");
        println!("   - Geographic restrictions or different page layout");

        // Don't fail the test immediately, but save debug info
        if std::env::var("TARZI_DEBUG").is_ok() {
            std::fs::write("debug_google_no_results.html", &html_content).ok();
            println!("Debug HTML saved to debug_google_no_results.html");
        }
    } else {
        assert!(
            results.len() <= limit,
            "Should not exceed the requested limit"
        );

        // Validate each result structure
        for (i, result) in results.iter().enumerate() {
            println!("Result {}: {} - {}", i + 1, result.title, result.url);

            // Basic validation
            assert!(!result.title.is_empty(), "Title should not be empty");
            assert_eq!(result.rank, i + 1, "Rank should be sequential");

            // URL validation (Google might have empty URLs for some results)
            if !result.url.is_empty() {
                assert!(
                    result.url.starts_with("http://")
                        || result.url.starts_with("https://")
                        || result.url.starts_with("/"),
                    "URL should be properly formatted or relative: {}",
                    result.url
                );
            }

            // Content validation (for "rust programming language" search)
            let lower_title = result.title.to_lowercase();
            let lower_snippet = result.snippet.to_lowercase();
            let contains_rust = lower_title.contains("rust")
                || lower_snippet.contains("rust")
                || lower_title.contains("programming")
                || lower_snippet.contains("programming");

            if !contains_rust {
                println!(
                    "Warning: Result {} may not be relevant to search query",
                    i + 1
                );
            }
        }

        println!("✓ All results validated successfully");
    }

    // Test with different limits
    let small_limit = 2;
    let small_results = parser.parse(&html_content, small_limit).unwrap();
    assert!(small_results.len() <= small_limit);
    assert!(small_results.len() <= results.len());
    println!("✓ Parser correctly handles different limits");

    // Test with empty HTML
    let empty_results = parser.parse("", 5).unwrap();
    assert!(empty_results.is_empty());
    println!("✓ Parser correctly handles empty HTML");

    println!("🎉 Real-world Google parser integration test completed successfully!");
}

#[tokio::test]
async fn test_brave_parser_real_world_integration() {
    // Skip test if WebDriver is not available
    if !is_webdriver_available().await {
        println!("Skipping Brave real-world integration test: WebDriver not available");
        println!("To run this test, start a WebDriver server (e.g., geckodriver on port 4444)");
        return;
    }

    println!("Starting real-world Brave search integration test...");

    // Perform a real search with timeout
    let search_query = "rust programming language";
    let html_content = match tokio::time::timeout(
        Duration::from_secs(30), // Shorter timeout
        perform_brave_search(search_query),
    )
    .await
    {
        Ok(Ok(html)) => html,
        Ok(Err(e)) => {
            println!("⚠️  Brave search failed: {e}");
            println!("This is likely due to Brave's anti-automation measures or CAPTCHA.");
            println!("The BraveParser logic is tested separately in unit tests.");
            return; // Skip the test gracefully
        }
        Err(_) => {
            println!("⚠️  Brave search timed out after 30 seconds");
            println!("This is likely due to Brave's anti-automation measures or CAPTCHA.");
            println!("The BraveParser logic is tested separately in unit tests.");
            return; // Skip the test gracefully
        }
    };

    // Verify we got actual Brave HTML
    assert!(html_content.contains("brave.com") || html_content.contains("Brave"));
    assert!(html_content.len() > 5000); // Brave pages are typically quite large
    println!("✓ Successfully retrieved Brave search results HTML");

    // Create BraveParser and parse the results
    let parser = BraveParser::new();
    assert_eq!(parser.name(), "BraveParser");
    assert!(parser.supports(&SearchEngineType::BraveSearch));
    println!("✓ BraveParser created and validated");

    // Parse the real HTML
    let limit = 5;
    let results = match parser.parse(&html_content, limit) {
        Ok(results) => results,
        Err(e) => {
            eprintln!("Failed to parse Brave HTML: {e}");
            // Save HTML for debugging if needed
            if std::env::var("TARZI_DEBUG").is_ok() {
                std::fs::write("debug_brave.html", &html_content).ok();
                println!("Debug HTML saved to debug_brave.html");
            }
            panic!("Parser failed: {e}");
        }
    };

    println!("✓ Successfully parsed {} search results", results.len());

    // Validate the parsed results
    if results.is_empty() {
        println!("⚠️  Warning: No search results found. This could be due to:");
        println!("   - Brave blocking automated requests or showing CAPTCHA");
        println!("   - Changes in Brave's HTML structure");
        println!("   - Geographic restrictions or different page layout");

        // Don't fail the test immediately, but save debug info
        if std::env::var("TARZI_DEBUG").is_ok() {
            std::fs::write("debug_brave_no_results.html", &html_content).ok();
            println!("Debug HTML saved to debug_brave_no_results.html");
        }
    } else {
        assert!(
            results.len() <= limit,
            "Should not exceed the requested limit"
        );

        // Validate each result structure
        for (i, result) in results.iter().enumerate() {
            println!("Result {}: {} - {}", i + 1, result.title, result.url);

            // Basic validation
            assert!(!result.title.is_empty(), "Title should not be empty");
            assert_eq!(result.rank, i + 1, "Rank should be sequential");

            // URL validation (Brave might have empty URLs for some results)
            if !result.url.is_empty() {
                assert!(
                    result.url.starts_with("http://")
                        || result.url.starts_with("https://")
                        || result.url.starts_with("/"),
                    "URL should be properly formatted or relative: {}",
                    result.url
                );
            }

            // Content validation (for "rust programming language" search)
            let lower_title = result.title.to_lowercase();
            let lower_snippet = result.snippet.to_lowercase();
            let contains_rust = lower_title.contains("rust")
                || lower_snippet.contains("rust")
                || lower_title.contains("programming")
                || lower_snippet.contains("programming");

            if !contains_rust {
                println!(
                    "Warning: Result {} may not be relevant to search query",
                    i + 1
                );
            }
        }

        println!("✓ All results validated successfully");
    }

    // Test with different limits
    let small_limit = 2;
    let small_results = parser.parse(&html_content, small_limit).unwrap();
    assert!(small_results.len() <= small_limit);
    assert!(small_results.len() <= results.len());
    println!("✓ Parser correctly handles different limits");

    // Test with empty HTML
    let empty_results = parser.parse("", 5).unwrap();
    assert!(empty_results.is_empty());
    println!("✓ Parser correctly handles empty HTML");

    println!("🎉 Real-world Brave parser integration test completed successfully!");
}

#[tokio::test]
async fn test_baidu_parser_real_world_integration() {
    // Skip test if WebDriver is not available
    if !is_webdriver_available().await {
        println!("Skipping Baidu real-world integration test: WebDriver not available");
        println!("To run this test, start a WebDriver server (e.g., geckodriver on port 4444)");
        return;
    }

    println!("Starting real-world Baidu search integration test...");

    // Perform a real search with timeout
    let search_query = "rust 编程语言"; // "rust programming language" in Chinese
    let html_content = match tokio::time::timeout(
        Duration::from_secs(30), // Shorter timeout
        perform_baidu_search(search_query),
    )
    .await
    {
        Ok(Ok(html)) => html,
        Ok(Err(e)) => {
            println!("⚠️  Baidu search failed: {e}");
            println!(
                "This is likely due to Baidu's anti-automation measures or regional restrictions."
            );
            println!("The BaiduParser logic is tested separately in unit tests.");
            return; // Skip the test gracefully
        }
        Err(_) => {
            println!("⚠️  Baidu search timed out after 30 seconds");
            println!(
                "This is likely due to Baidu's anti-automation measures or regional restrictions."
            );
            println!("The BaiduParser logic is tested separately in unit tests.");
            return; // Skip the test gracefully
        }
    };

    // Verify we got actual Baidu HTML
    assert!(html_content.contains("baidu.com") || html_content.contains("百度"));
    assert!(html_content.len() > 5000); // Baidu pages are typically quite large
    println!("✓ Successfully retrieved Baidu search results HTML");

    // Create BaiduParser and parse the results
    let parser = BaiduParser::new();
    assert_eq!(parser.name(), "BaiduParser");
    assert!(parser.supports(&SearchEngineType::Baidu));
    println!("✓ BaiduParser created and validated");

    // Parse the real HTML
    let limit = 5;
    let results = match parser.parse(&html_content, limit) {
        Ok(results) => results,
        Err(e) => {
            eprintln!("Failed to parse Baidu HTML: {e}");
            // Save HTML for debugging if needed
            if std::env::var("TARZI_DEBUG").is_ok() {
                std::fs::write("debug_baidu.html", &html_content).ok();
                println!("Debug HTML saved to debug_baidu.html");
            }
            panic!("Parser failed: {e}");
        }
    };

    println!("✓ Successfully parsed {} search results", results.len());

    // Validate the parsed results
    if results.is_empty() {
        println!("⚠️  Warning: No search results found. This could be due to:");
        println!("   - Baidu blocking automated requests or showing CAPTCHA");
        println!("   - Changes in Baidu's HTML structure");
        println!("   - Regional restrictions or different page layout");
        println!("   - All results filtered out as ads");

        // Don't fail the test immediately, but save debug info
        if std::env::var("TARZI_DEBUG").is_ok() {
            std::fs::write("debug_baidu_no_results.html", &html_content).ok();
            println!("Debug HTML saved to debug_baidu_no_results.html");
        }
    } else {
        assert!(
            results.len() <= limit,
            "Should not exceed the requested limit"
        );

        // Validate each result structure
        for (i, result) in results.iter().enumerate() {
            println!("Result {}: {} - {}", i + 1, result.title, result.url);

            // Basic validation
            assert!(!result.title.is_empty(), "Title should not be empty");
            assert_eq!(result.rank, i + 1, "Rank should be sequential");

            // URL validation (Baidu might have empty URLs for some results)
            if !result.url.is_empty() {
                assert!(
                    result.url.starts_with("http://")
                        || result.url.starts_with("https://")
                        || result.url.starts_with("/"),
                    "URL should be properly formatted or relative: {}",
                    result.url
                );
            }

            // Content validation (for "rust 编程语言" search)
            let lower_title = result.title.to_lowercase();
            let lower_snippet = result.snippet.to_lowercase();
            let contains_rust = lower_title.contains("rust")
                || lower_snippet.contains("rust")
                || lower_title.contains("编程")
                || lower_snippet.contains("编程")
                || lower_title.contains("programming")
                || lower_snippet.contains("programming");

            if !contains_rust {
                println!(
                    "Warning: Result {} may not be relevant to search query",
                    i + 1
                );
            }
        }

        println!("✓ All results validated successfully");
    }

    // Test with different limits
    let small_limit = 2;
    let small_results = parser.parse(&html_content, small_limit).unwrap();
    assert!(small_results.len() <= small_limit);
    assert!(small_results.len() <= results.len());
    println!("✓ Parser correctly handles different limits");

    // Test with empty HTML
    let empty_results = parser.parse("", 5).unwrap();
    assert!(empty_results.is_empty());
    println!("✓ Parser correctly handles empty HTML");

    println!("🎉 Real-world Baidu parser integration test completed successfully!");
}