-
Notifications
You must be signed in to change notification settings - Fork 1.6k
Expand file tree
/
Copy pathbrowser_crawler.test.ts
More file actions
1188 lines (987 loc) · 41.9 KB
/
Copy pathbrowser_crawler.test.ts
File metadata and controls
1188 lines (987 loc) · 41.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import type { Server } from 'node:http';
import type { BrowserPool, PuppeteerController } from '@crawlee/browser-pool';
import {
BROWSER_POOL_EVENTS,
BrowserPool as BrowserPoolClass,
OperatingSystemsName,
PuppeteerPlugin,
RemoteBrowserPool,
} from '@crawlee/browser-pool';
import { BLOCKED_STATUS_CODES, MemoryStorageBackend, serviceLocator, SessionPool } from '@crawlee/core';
import type { PuppeteerGoToOptions } from '@crawlee/puppeteer';
import { EnqueueStrategy, ProxyConfiguration, Request, RequestList, RequestState, Session } from '@crawlee/puppeteer';
import { sleep } from '@crawlee/utils';
// @ts-ignore This only throws when compiled against puppeteer 25+ (ESM only), we only import types, so its alllll gooooood
import type { HTTPResponse } from 'puppeteer';
// @ts-ignore This only throws when compiled against puppeteer 25+ (ESM only), vitest executes tests as ESM, so its alllll gooooood
import puppeteer from 'puppeteer';
import { runExampleComServer } from '../../shared/_helper.js';
import { ENV_VARS } from '@apify/consts';
import log from '@apify/log';
import type { TestCrawlingContext } from './basic_browser_crawler.js';
import { BrowserCrawlerTest } from './basic_browser_crawler.js';
import { ISession } from '@crawlee/types';
describe('BrowserCrawler', () => {
let prevEnvHeadless: string;
let logLevel: number;
let serverAddress = 'http://localhost:';
let port: number;
let server: Server;
beforeAll(async () => {
prevEnvHeadless = process.env.CRAWLEE_HEADLESS!;
process.env.CRAWLEE_HEADLESS = '1';
logLevel = log.getLevel();
log.setLevel(log.LEVELS.ERROR);
[server, port] = await runExampleComServer();
serverAddress += port;
});
afterAll(async () => {
log.setLevel(logLevel);
process.env.CRAWLEE_HEADLESS = prevEnvHeadless;
server.close();
});
beforeEach(() => {
serviceLocator.setStorageBackend(new MemoryStorageBackend());
});
test('should work', async () => {
const puppeteerPlugin = new PuppeteerPlugin(puppeteer);
const sources = [
{ url: `${serverAddress}/?q=1` },
{ url: `${serverAddress}/?q=2` },
{ url: `${serverAddress}/?q=3` },
{ url: `${serverAddress}/?q=4` },
{ url: `${serverAddress}/?q=5` },
{ url: `${serverAddress}/?q=6` },
];
const sourcesCopy = JSON.parse(JSON.stringify(sources));
const processed: Request[] = [];
const failed: Request[] = [];
const requestList = await RequestList.open(null, sources);
const requestHandler = async ({ page, request, response }: TestCrawlingContext) => {
await page.waitForSelector('title');
expect(response!.status()).toBe(200);
request.userData.title = await page.title();
processed.push(request);
};
const browserCrawler = new BrowserCrawlerTest({
browserPoolOptions: {
browserPlugins: [puppeteerPlugin],
},
requestList,
minConcurrency: 1,
maxConcurrency: 1,
requestHandler,
failedRequestHandler: async ({ request }) => {
failed.push(request);
},
});
await browserCrawler.run();
expect(browserCrawler.autoscaledPool!.minConcurrency).toBe(1);
expect(processed).toHaveLength(6);
expect(failed).toHaveLength(0);
processed.forEach((request, id) => {
expect(request.url).toEqual(sourcesCopy[id].url);
expect(request.userData.title).toBe('Example Domain');
});
});
test('should teardown browser pool', async () => {
const puppeteerPlugin = new PuppeteerPlugin(puppeteer);
const requestList = await RequestList.open({
sources: [{ url: 'http://example.com/?q=1' }],
});
const browserCrawler = new BrowserCrawlerTest({
browserPoolOptions: {
browserPlugins: [puppeteerPlugin],
},
requestList,
requestHandler: async () => {},
maxRequestRetries: 1,
});
// Spy on destroy and track if it was called
let destroyCalled = false;
const ownedPool = browserCrawler.browserPool as BrowserPool;
const originalDestroy = ownedPool.destroy.bind(ownedPool);
ownedPool.destroy = async () => {
destroyCalled = true;
return originalDestroy();
};
await browserCrawler.run();
expect(destroyCalled).toBe(true);
});
test('should not tear down a user-supplied browser pool', async () => {
const puppeteerPlugin = new PuppeteerPlugin(puppeteer);
const externalPool = new BrowserPoolClass({ browserPlugins: [puppeteerPlugin] });
try {
const requestList = await RequestList.open({
sources: [{ url: 'http://example.com/?q=1' }],
});
const browserCrawler = new BrowserCrawlerTest({
browserPool: externalPool,
requestList,
requestHandler: async () => {},
maxRequestRetries: 1,
});
expect(browserCrawler.browserPool).toBe(externalPool);
let destroyCalled = false;
const originalDestroy = externalPool.destroy.bind(externalPool);
externalPool.destroy = async () => {
destroyCalled = true;
return originalDestroy();
};
await browserCrawler.run();
expect(destroyCalled).toBe(false);
} finally {
await externalPool.destroy();
}
});
test('builds and owns a RemoteBrowserPool from the remoteBrowser option', async () => {
const crawler = new BrowserCrawlerTest({
remoteBrowser: { endpoint: 'ws://remote:9222', maxOpenBrowsers: 2 },
browserPoolOptions: { browserPlugins: [new PuppeteerPlugin(puppeteer)] },
requestHandler: async () => {},
});
expect(crawler.browserPool).toBeInstanceOf(RemoteBrowserPool);
expect((crawler.browserPool as RemoteBrowserPool).maxOpenBrowsers).toBe(2);
await (crawler.browserPool as RemoteBrowserPool).destroy();
});
test('uses browserPool and ignores remoteBrowser when both are set', async () => {
const externalPool = new BrowserPoolClass({ browserPlugins: [new PuppeteerPlugin(puppeteer)] });
try {
const crawler = new BrowserCrawlerTest({
browserPool: externalPool,
remoteBrowser: { endpoint: 'ws://remote:9222' },
requestHandler: async () => {},
});
expect(crawler.browserPool).toBe(externalPool);
} finally {
await externalPool.destroy();
}
});
test('should retire session after TimeoutError', async () => {
const puppeteerPlugin = new PuppeteerPlugin(puppeteer);
const requestList = await RequestList.open({
sources: [{ url: 'http://example.com/?q=1' }],
});
class TimeoutError extends Error {}
let markBadCalled = false;
let sessionGoto!: ISession;
const browserCrawler = new (class extends BrowserCrawlerTest {
protected override async _navigationHandler(
ctx: TestCrawlingContext,
): Promise<HTTPResponse | null | undefined> {
sessionGoto = ctx.session!;
const originalMarkBad = sessionGoto.markBad.bind(sessionGoto);
sessionGoto.markBad = () => {
markBadCalled = true;
return originalMarkBad();
};
throw new TimeoutError();
}
})({
browserPoolOptions: {
browserPlugins: [puppeteerPlugin],
},
requestList,
requestHandler: async () => {},
maxRequestRetries: 1,
});
await browserCrawler.run();
expect(markBadCalled).toBe(true);
});
test('should evaluate preNavigationHooks', async () => {
const puppeteerPlugin = new PuppeteerPlugin(puppeteer);
const requestList = await RequestList.open({
sources: [{ url: 'http://example.com/?q=1' }],
});
const hook = vi.fn(async () => {
await sleep(10);
});
const browserCrawler = new BrowserCrawlerTest({
browserPoolOptions: {
browserPlugins: [puppeteerPlugin],
},
requestList,
requestHandler: async () => {},
maxRequestRetries: 0,
preNavigationHooks: [hook],
});
await browserCrawler.run();
expect(hook).toHaveBeenCalled();
});
test('should evaluate postNavigationHooks', async () => {
const puppeteerPlugin = new PuppeteerPlugin(puppeteer);
const requestList = await RequestList.open({
sources: [{ url: `${serverAddress}/?q=1` }],
});
const hook = vi.fn(async () => {
await sleep(10);
});
const browserCrawler = new BrowserCrawlerTest({
browserPoolOptions: {
browserPlugins: [puppeteerPlugin],
},
requestList,
requestHandler: async () => {},
maxRequestRetries: 0,
postNavigationHooks: [hook],
});
await browserCrawler.run();
expect(hook).toHaveBeenCalled();
});
test('postNavigationHooks can override response, observed downstream', async () => {
const puppeteerPlugin = new PuppeteerPlugin(puppeteer);
const requestList = await RequestList.open({
sources: [{ url: `${serverAddress}/?q=1` }],
});
const observed: { fromSecondHook?: number; fromHandler?: number } = {};
const fakeStatus = 418;
const browserCrawler = new BrowserCrawlerTest({
browserPoolOptions: {
browserPlugins: [puppeteerPlugin],
},
requestList,
maxRequestRetries: 0,
postNavigationHooks: [
async ({ response }) => ({
response: new Proxy(response, {
get(target, key, receiver) {
if (key === 'status') return () => fakeStatus;
return Reflect.get(target, key, receiver);
},
}),
}),
async ({ response }) => {
observed.fromSecondHook = response.status();
},
],
requestHandler: async ({ response }) => {
observed.fromHandler = response.status();
},
});
await browserCrawler.run();
expect(observed.fromSecondHook).toBe(fakeStatus);
expect(observed.fromHandler).toBe(fakeStatus);
});
test('errorHandler has open page', async () => {
const puppeteerPlugin = new PuppeteerPlugin(puppeteer);
const requestList = await RequestList.open({
sources: [{ url: `${serverAddress}/?q=1` }],
});
const result: string[] = [];
const browserCrawler = new BrowserCrawlerTest({
browserPoolOptions: {
browserPlugins: [puppeteerPlugin],
},
requestList,
requestHandler: async (ctx) => {
throw new Error('Test error');
},
maxRequestRetries: 1,
errorHandler: async (ctx, error) => {
result.push(await ctx.page!.evaluate(() => window.location.origin));
},
});
await browserCrawler.run();
expect(result.length).toBe(1);
expect(result[0]).toBe(serverAddress);
});
// see https://github.com/apify/crawlee/issues/3873
test('errorHandler has open page after non-timeout navigation error', async () => {
const puppeteerPlugin = new PuppeteerPlugin(puppeteer);
const requestList = await RequestList.open({
sources: [{ url: `${serverAddress}/?q=1` }],
});
const pageClosedStates: boolean[] = [];
const browserCrawler = new (class extends BrowserCrawlerTest {
protected override async _navigationHandler(): Promise<HTTPResponse | null | undefined> {
throw new Error('net::ERR_NAME_NOT_RESOLVED');
}
})({
browserPoolOptions: {
browserPlugins: [puppeteerPlugin],
},
requestList,
requestHandler: async () => {},
maxRequestRetries: 1,
errorHandler: async (ctx) => {
pageClosedStates.push(ctx.page!.isClosed());
},
});
await browserCrawler.run();
expect(pageClosedStates).toHaveLength(1);
expect(pageClosedStates[0]).toBe(false);
});
test('should correctly track request.state', async () => {
const puppeteerPlugin = new PuppeteerPlugin(puppeteer);
const sources = [{ url: `${serverAddress}/?q=1` }];
const requestList = await RequestList.open(null, sources);
const requestStates: RequestState[] = [];
const browserCrawler = new BrowserCrawlerTest({
browserPoolOptions: {
browserPlugins: [puppeteerPlugin],
},
requestList,
preNavigationHooks: [
async ({ request }) => {
requestStates.push(request.state);
},
],
postNavigationHooks: [
async ({ request }) => {
requestStates.push(request.state);
},
],
requestHandler: async ({ request }) => {
requestStates.push(request.state);
throw new Error('Error');
},
maxRequestRetries: 1,
errorHandler: async ({ request }) => {
requestStates.push(request.state);
},
});
await browserCrawler.run();
expect(requestStates).toEqual([
RequestState.BEFORE_NAV,
RequestState.AFTER_NAV,
RequestState.REQUEST_HANDLER,
RequestState.ERROR_HANDLER,
RequestState.BEFORE_NAV,
RequestState.AFTER_NAV,
RequestState.REQUEST_HANDLER,
]);
});
test('should allow modifying gotoOptions by pre navigation hooks', async () => {
const puppeteerPlugin = new PuppeteerPlugin(puppeteer);
const requestList = await RequestList.open({
sources: [{ url: `${serverAddress}/?q=1` }],
});
let optionsGoto: PuppeteerGoToOptions;
const browserCrawler = new (class extends BrowserCrawlerTest {
protected override async _navigationHandler(
ctx: TestCrawlingContext,
gotoOptions: PuppeteerGoToOptions,
): Promise<HTTPResponse | null | undefined> {
optionsGoto = gotoOptions;
return ctx.page.goto(ctx.request.url, gotoOptions);
}
})({
browserPoolOptions: {
browserPlugins: [puppeteerPlugin],
},
requestList,
requestHandler: async () => {},
maxRequestRetries: 0,
preNavigationHooks: [
async ({ gotoOptions }) => {
gotoOptions.timeout = 60000;
},
],
});
await browserCrawler.run();
expect(optionsGoto!.timeout).toEqual(60000);
});
test('should ignore errors in Page.close()', async () => {
const puppeteerPlugin = new PuppeteerPlugin(puppeteer);
for (let i = 0; i < 2; i++) {
const requestList = await RequestList.open({
sources: [{ url: `${serverAddress}/?q=1` }],
});
let failedCalled = false;
const browserCrawler = new BrowserCrawlerTest({
browserPoolOptions: {
browserPlugins: [puppeteerPlugin],
},
requestList,
requestHandler: async ({ page }) => {
page.close = async () => {
if (i === 0) {
throw new Error();
} else {
return Promise.reject(new Error());
}
};
return Promise.resolve();
},
failedRequestHandler: async () => {
failedCalled = true;
},
});
await browserCrawler.run();
expect(failedCalled).toBe(false);
}
});
test('should respect the requestHandlerTimeoutSecs option', async () => {
const puppeteerPlugin = new PuppeteerPlugin(puppeteer);
const requestList = await RequestList.open({
sources: [{ url: `${serverAddress}/?q=1` }],
});
const callSpy = vitest.fn();
// Use a very long delay for "bad" so it can never fire during test execution.
// The test verifies that the 500ms timeout aborts the handler before "bad" would fire.
const browserCrawler = new BrowserCrawlerTest({
browserPoolOptions: {
browserPlugins: [puppeteerPlugin],
},
requestList,
requestHandler: async () => {
setTimeout(() => callSpy('good'), 300);
setTimeout(() => callSpy('bad'), 60_000);
await new Promise(() => {});
},
requestHandlerTimeoutSecs: 0.5,
maxRequestRetries: 0,
});
await browserCrawler.run();
expect(callSpy).toBeCalledTimes(1);
expect(callSpy).toBeCalledWith('good');
});
test('should not throw without SessionPool', async () => {
const puppeteerPlugin = new PuppeteerPlugin(puppeteer);
const requestList = await RequestList.open({
sources: [{ url: 'http://example.com/?q=1' }],
});
const browserCrawler = new BrowserCrawlerTest({
browserPoolOptions: {
browserPlugins: [puppeteerPlugin],
},
requestList,
requestHandler: async () => {},
});
expect(browserCrawler).toBeDefined();
});
test('should correctly set session pool options', async () => {
const puppeteerPlugin = new PuppeteerPlugin(puppeteer);
const requestList = await RequestList.open({
sources: [{ url: 'http://example.com/?q=1' }],
});
const crawler = new BrowserCrawlerTest({
requestList,
browserPoolOptions: {
browserPlugins: [puppeteerPlugin],
},
saveResponseCookies: false,
sessionPool: new SessionPool({
sessionOptions: {
maxUsageCount: 1,
},
persistStateKeyValueStoreId: 'abc',
}),
requestHandler: async () => {},
});
// @ts-expect-error Accessing private prop
expect(crawler.sessionPool.sessionOptions.maxUsageCount).toBe(1);
// @ts-expect-error Accessing private prop
expect(crawler.sessionPool.persistStateKeyValueStoreId).toBe('abc');
});
test.skip('should persist cookies per session', async () => {
const puppeteerPlugin = new PuppeteerPlugin(puppeteer);
const name = `list-${Math.random()}`;
const requestList = await RequestList.open({
persistStateKey: name,
persistRequestsKey: name,
sources: [
{ url: 'http://example.com/?q=1' },
{ url: 'http://example.com/?q=2' },
{ url: 'http://example.com/?q=3' },
{ url: 'http://example.com/?q=4' },
],
});
const goToPageSessions = [];
const loadedCookies: string[] = [];
const browserCrawler = new BrowserCrawlerTest({
browserPoolOptions: {
browserPlugins: [puppeteerPlugin],
},
requestList,
saveResponseCookies: true,
requestHandler: async ({ session, request }) => {
loadedCookies.push(session.cookieJar.getCookieStringSync(request.url));
return Promise.resolve();
},
preNavigationHooks: [
async ({ session, page }) => {
await page.setCookie({
name: 'TEST',
value: '12321312312',
domain: 'example.com',
expires: Date.now() + 100000,
});
goToPageSessions.push(session);
},
],
});
await browserCrawler.run();
expect(loadedCookies).toHaveLength(4);
loadedCookies.forEach((cookie) => {
// TODO this test is flaky in CI and we need some more info to debug why.
if (cookie !== 'TEST=12321312312') {
// for some reason, the CI failures report the first cookie to be just empty string
console.log('loadedCookies:');
console.dir(loadedCookies);
}
expect(cookie).toEqual('TEST=12321312312');
});
});
test('should throw on "blocked" status codes', async () => {
const puppeteerPlugin = new PuppeteerPlugin(puppeteer);
const baseUrl = 'https://example.com/';
const sources = BLOCKED_STATUS_CODES.map((statusCode) => {
return {
url: baseUrl + statusCode,
userData: { statusCode },
};
});
const requestList = await RequestList.open(null, sources);
let called = false;
const failedRequests: Request[] = [];
const crawler = new BrowserCrawlerTest({
browserPoolOptions: {
browserPlugins: [puppeteerPlugin],
},
requestList,
saveResponseCookies: false,
maxRequestRetries: 0,
requestHandler: async () => {
called = true;
},
failedRequestHandler: async ({ request }) => {
failedRequests.push(request);
},
});
// @ts-expect-error Overriding protected method
crawler._navigationHandler = async ({ request }) => {
return { status: () => request.userData.statusCode };
};
await crawler.run();
expect(failedRequests.length).toBe(3);
failedRequests.forEach((fr) => {
const [msg] = fr.errorMessages;
expect(msg).toContain(`Request blocked - received ${fr.userData.statusCode} status code.`);
});
expect(called).toBe(false);
});
test('retryOnBlocked should retry on Cloudflare challenge', async () => {
const puppeteerPlugin = new PuppeteerPlugin(puppeteer);
const urls = [new URL('/special/cloudflareBlocking', serverAddress).href];
const maxRequestRetries = 1;
let processed = false;
const errorMessages: string[] = [];
const crawler = new BrowserCrawlerTest({
browserPoolOptions: {
browserPlugins: [puppeteerPlugin],
},
retryOnBlocked: true,
maxRequestRetries,
requestHandler: async ({ page, response }) => {
processed = true;
},
failedRequestHandler: async ({ request }) => {
errorMessages.push(...request.errorMessages);
},
});
await crawler.run(urls);
expect(errorMessages).toHaveLength(urls.length * (maxRequestRetries + 1));
expect(errorMessages.every((x) => x.includes('Detected a session error, retiring session...'))).toBe(true);
expect(processed).toBe(false);
});
test('retryOnBlocked throws on "blocked" status codes', async () => {
const puppeteerPlugin = new PuppeteerPlugin(puppeteer);
const baseUrl = 'https://example.com/';
const sources = BLOCKED_STATUS_CODES.map((statusCode) => {
return {
url: baseUrl + statusCode,
userData: { statusCode },
};
});
const requestList = await RequestList.open(null, sources);
const maxRequestRetries = 1;
const errorMessages: string[] = [];
let processed = false;
const crawler = new BrowserCrawlerTest({
browserPoolOptions: {
browserPlugins: [puppeteerPlugin],
},
requestList,
retryOnBlocked: true,
maxRequestRetries,
requestHandler: async () => {
processed = true;
},
failedRequestHandler: async ({ request }) => {
errorMessages.push(...request.errorMessages);
},
});
// @ts-expect-error Overriding protected method
crawler._navigationHandler = async ({ request }) => {
return { status: () => request.userData.statusCode };
};
await crawler.run();
expect(errorMessages.length).toBe(sources.length * (maxRequestRetries + 1));
expect(errorMessages.every((x) => x.includes('Detected a session error, retiring session...'))).toBe(true);
expect(processed).toBe(false);
});
test('should throw on "blocked" status codes (retire session)', async () => {
const puppeteerPlugin = new PuppeteerPlugin(puppeteer);
const baseUrl = 'https://example.com/';
const sources = BLOCKED_STATUS_CODES.map((statusCode) => {
return {
url: baseUrl + statusCode,
userData: { statusCode },
};
});
const requestList = await RequestList.open(null, sources);
let called = false;
const failedRequests: Request[] = [];
const crawler = new BrowserCrawlerTest({
browserPoolOptions: {
browserPlugins: [puppeteerPlugin],
},
requestList,
saveResponseCookies: false,
maxRequestRetries: 0,
requestHandler: async () => {
called = true;
},
failedRequestHandler: async ({ request }) => {
failedRequests.push(request);
},
});
// @ts-expect-error Overriding protected method
crawler._navigationHandler = async ({ request }) => {
return { status: () => request.userData.statusCode };
};
await crawler.run();
expect(failedRequests.length).toBe(3);
failedRequests.forEach((fr) => {
const [msg] = fr.errorMessages;
expect(msg).toContain(`Request blocked - received ${fr.userData.statusCode} status code.`);
});
expect(called).toBe(false);
});
test('should retire browser with session', async () => {
const puppeteerPlugin = new PuppeteerPlugin(puppeteer);
const requestList = await RequestList.open({
sources: [{ url: 'http://example.com/?q=1' }],
});
let retiredBrowserCount = 0;
const browserCrawler = new BrowserCrawlerTest({
browserPoolOptions: {
browserPlugins: [puppeteerPlugin],
},
requestList,
requestHandler: async ({ session }) => {
session!.retire();
},
maxRequestRetries: 1,
});
(browserCrawler.browserPool as BrowserPool).on(BROWSER_POOL_EVENTS.BROWSER_RETIRED, () => {
retiredBrowserCount += 1;
});
await browserCrawler.run();
expect(retiredBrowserCount).toBeGreaterThan(0);
});
test('should increment session usage correctly', async () => {
const puppeteerPlugin = new PuppeteerPlugin(puppeteer);
const sessionUsageHistory: number[] = [];
const browserCrawler = new BrowserCrawlerTest({
browserPoolOptions: {
browserPlugins: [puppeteerPlugin],
},
sessionPool: new SessionPool({
maxPoolSize: 1,
}),
requestHandler: async ({ session }) => {
sessionUsageHistory.push((session as Session).usageCount);
},
});
await browserCrawler.run([
{ url: `${serverAddress}/?q=1` },
{ url: `${serverAddress}/?q=2` },
{ url: `${serverAddress}/?q=3` },
{ url: `${serverAddress}/?q=4` },
{ url: `${serverAddress}/?q=5` },
{ url: `${serverAddress}/?q=6` },
]);
expect(sessionUsageHistory).toEqual([0, 1, 2, 3, 4, 5]);
});
test('should allow using fingerprints from browser pool', async () => {
const puppeteerPlugin = new PuppeteerPlugin(puppeteer);
const pool = new BrowserPoolClass({
browserPlugins: [puppeteerPlugin],
useFingerprints: true,
fingerprintOptions: {
fingerprintGeneratorOptions: {
operatingSystems: [OperatingSystemsName.windows],
},
},
});
try {
const requestList = await RequestList.open({
sources: [{ url: `${serverAddress}/?q=1` }],
});
const browserCrawler = new BrowserCrawlerTest({
browserPool: pool,
requestList,
requestHandler: async ({ page }) => {
const controller = pool.getBrowserControllerByPage(page);
expect(controller?.launchContext.fingerprint).toBeDefined();
},
});
await browserCrawler.run();
expect.hasAssertions();
} finally {
await pool.destroy();
}
});
describe('proxy', () => {
// This test manipulates environment variables, so it must NOT be run concurrently
test('browser should launch with rotated custom proxy', async () => {
const puppeteerPlugin = new PuppeteerPlugin(puppeteer);
process.env[ENV_VARS.PROXY_PASSWORD] = 'abc123';
const requestList = await RequestList.open({
sources: [
{ url: `${serverAddress}/?q=1` },
{ url: `${serverAddress}/?q=2` },
{ url: `${serverAddress}/?q=3` },
],
});
const proxyConfiguration = new ProxyConfiguration({
proxyUrls: ['http://proxy.com:1111', 'http://proxy.com:2222', 'http://proxy.com:3333'],
});
const browserProxies: string[] = [];
const browserCrawler = new BrowserCrawlerTest({
browserPoolOptions: {
browserPlugins: [puppeteerPlugin],
maxOpenPagesPerBrowser: 1,
retireBrowserAfterPageCount: 1,
},
requestList,
requestHandler: async () => {},
proxyConfiguration,
maxRequestRetries: 0,
maxConcurrency: 1,
});
(browserCrawler.browserPool as BrowserPool).postLaunchHooks.push((_pageId, browserController) => {
browserProxies.push((browserController as PuppeteerController).launchContext.proxyUrl!);
});
await browserCrawler.run();
// @ts-expect-error Accessing private property
const proxiesToUse = proxyConfiguration.proxyUrls!;
for (const proxyUrl of proxiesToUse) {
expect(browserProxies.includes(new URL(proxyUrl!).href.slice(0, -1))).toBeTruthy();
}
delete process.env[ENV_VARS.PROXY_PASSWORD];
});
test('proxy rotation on error works as expected', async () => {
const puppeteerPlugin = new PuppeteerPlugin(puppeteer);
const requestList = await RequestList.open({
sources: [
{ url: 'http://example.com/?q=1' },
{ url: 'http://example.com/?q=2' },
{ url: 'http://example.com/?q=3' },
{ url: 'http://example.com/?q=4' },
],
});
const goodProxyUrl = 'http://good.proxy';
const proxyUrls = ['http://localhost', 'http://localhost:1234', goodProxyUrl];
const proxyConfiguration = new ProxyConfiguration({ proxyUrls });
const requestHandler = vitest.fn();
const browserCrawler = new (class extends BrowserCrawlerTest {
protected override async _navigationHandler(
ctx: TestCrawlingContext,
): Promise<HTTPResponse | null | undefined> {
const proxyInfo = ctx.session?.proxyInfo;
if (proxyInfo!.url !== goodProxyUrl) {
throw new Error('ERR_PROXY_CONNECTION_FAILED');
}
return null;
}
})({
browserPoolOptions: {
browserPlugins: [puppeteerPlugin],
},
requestList,
// Enough retries for every request to eventually be served on a session bound to the good proxy
// (proxy rotation interleaves with the request-manager order, so a few extra attempts are needed).
maxRequestRetries: 5,
maxConcurrency: 1,
proxyConfiguration,
requestHandler,
});
await expect(browserCrawler.run()).resolves.not.toThrow();
expect(requestHandler).toHaveBeenCalledTimes(4);
});
test('proxy rotation on error respects maxRequestRetries, calls failedRequestHandler', async () => {
const puppeteerPlugin = new PuppeteerPlugin(puppeteer);
const requestList = await RequestList.open({
sources: [
{ url: 'http://example.com/?q=1' },
{ url: 'http://example.com/?q=2' },
{ url: 'http://example.com/?q=3' },
{ url: 'http://example.com/?q=4' },
],
});
const proxyConfiguration = new ProxyConfiguration({
proxyUrls: ['http://localhost', 'http://localhost:1234'],
});
const failedRequestHandler = vitest.fn();
/**
* The first increment is the base case when the proxy is retrieved for the first time.
*/
let numberOfRotations = -(await requestList!.getTotalCount());
const browserCrawler = new (class extends BrowserCrawlerTest {
protected override async _navigationHandler(
ctx: TestCrawlingContext,
): Promise<HTTPResponse | null | undefined> {