Skip to content

Crawlee—A web scraping and browser automation library for Node.js to build reliable crawlers. In JavaScript and TypeScript. Extract data for AI, LLMs, RAG, or GPTs. Download HTML, PDF, JPG, PNG, and other files from websites. Works with Puppeteer, Playwright, Cheerio, JSDOM, and raw HTTP. Both headful and headless mode. With proxy rotation.

test(e2e): crawl local fixtures instead of the live demo store (#3922)

Martin Adámek5de7162311b4
diff --git a/test/e2e/adaptive-playwright-robots-file/actor/main.js b/test/e2e/adaptive-playwright-robots-file/actor/main.js
index d3355bc1f..24b73bef5 100644
--- a/test/e2e/adaptive-playwright-robots-file/actor/main.js
+++ b/test/e2e/adaptive-playwright-robots-file/actor/main.js
@@ -1,6 +1,48 @@
+import http from 'node:http';
+
import { AdaptivePlaywrightCrawler } from '@crawlee/playwright';
import { Actor } from 'apify';
+// Self-contained fixture: robots.txt disallows /cart and /checkout, and the
+// start page links to /cart alongside the allowed /collections/* pages. The
+// crawler may only reach the collections.
+const pages = {
+ '/robots.txt': ['User-agent: *', 'Disallow: /cart', 'Disallow: /checkout', ''].join('\n'),
+ '/': `<!doctype html>
+<html><head><title>Store</title></head>
+<body>
+ <a href="/cart">Cart</a>
+ <a href="/collections/audio">Audio</a>
+ <a href="/collections/tv">TV</a>
+</body></html>`,
+ // Every collection links back to /cart, so the robots.txt rule is what keeps
+ // it out of the dataset rather than a shortage of links to follow.
+ '/collections/audio': `<!doctype html>
+<html><head><title>Audio</title></head>
+<body><a href="/cart">Cart</a> <a href="/">Home</a></body></html>`,
+ '/collections/tv': `<!doctype html>
+<html><head><title>TV</title></head>
+<body><a href="/cart">Cart</a> <a href="/">Home</a></body></html>`,
+ '/cart': '<!doctype html><html><head><title>Cart</title></head><body>Cart</body></html>',
+ '/checkout': '<!doctype html><html><head><title>Checkout</title></head><body>Checkout</body></html>',
+};
+
+const server = http.createServer((req, res) => {
+ const body = pages[req.url];
+ if (body === undefined) {
+ res.statusCode = 404;
+ res.end('Not Found');
+ return;
+ }
+ const type = req.url === '/robots.txt' ? 'text/plain' : 'text/html';
+ res.writeHead(200, { 'content-type': `${type}; charset=utf-8` });
+ res.end(body);
+});
+
+await new Promise((resolve) => server.listen(0, '127.0.0.1', resolve));
+const { port } = server.address();
+const baseUrl = `http://127.0.0.1:${port}`;
+
await Actor.init({
storage:
process.env.STORAGE_IMPLEMENTATION === 'LOCAL'
@@ -9,8 +51,6 @@ await Actor.init({
});
const crawler = new AdaptivePlaywrightCrawler({
- // The store rate-limits the platform's shared egress IP, so crawl through a proxy.
- proxyConfiguration: await Actor.createProxyConfiguration(),
maxRequestsPerCrawl: 10,
respectRobotsTxtFile: true,
onSkippedRequest: (args) => crawler.log.warningOnce(`Request ${args.url} was skipped, reason: ${args.reason}`),
@@ -26,11 +66,13 @@ crawler.router.addDefaultHandler(async ({ log, request, enqueueLinks, pushData }
});
await crawler.run([
- 'https://warehouse-theme-metal.myshopify.com',
- 'https://warehouse-theme-metal.myshopify.com/checkout', // '/checkout' is disallowed by robots.txt
+ baseUrl,
+ `${baseUrl}/checkout`, // '/checkout' is disallowed by robots.txt
]);
const data = await crawler.getData();
console.table(data.items);
+server.close();
+
await Actor.exit({ exit: Actor.isAtHome() });
diff --git a/test/e2e/adaptive-playwright-robots-file/test.mjs b/test/e2e/adaptive-playwright-robots-file/test.mjs
index 9edc578f3..867ebb305 100644
--- a/test/e2e/adaptive-playwright-robots-file/test.mjs
+++ b/test/e2e/adaptive-playwright-robots-file/test.mjs
@@ -3,12 +3,12 @@ import { initialize, getActorTestDir, runActor, expect } from '../tools.mjs';
const testActorDirname = getActorTestDir(import.meta.url);
await initialize(testActorDirname);
-const { datasetItems } = await runActor(testActorDirname, 16384);
+const { stats, datasetItems } = await runActor(testActorDirname, 16384);
-const cartRequest = datasetItems.find((item) => item.url === 'https://warehouse-theme-metal.myshopify.com/cart');
-const checkoutRequest = datasetItems.find(
- (item) => item.url === 'https://warehouse-theme-metal.myshopify.com/checkout',
-);
+// Without this the two assertions below hold vacuously when the crawl never starts.
+await expect(stats.requestsFinished >= 1, 'All requests finished');
-await expect(!cartRequest, '/cart URL is not processed');
-await expect(!checkoutRequest, '/checkout URL is not processed');
+const paths = datasetItems.map((item) => new URL(item.url).pathname);
+
+await expect(!paths.includes('/cart'), '/cart URL is not processed');
+await expect(!paths.includes('/checkout'), '/checkout URL is not processed');
diff --git a/test/e2e/cheerio-enqueue-links-base/test.mjs b/test/e2e/cheerio-enqueue-links-base/test.mjs
index 448973a3e..1af2a7738 100644
--- a/test/e2e/cheerio-enqueue-links-base/test.mjs
+++ b/test/e2e/cheerio-enqueue-links-base/test.mjs
@@ -1,13 +1,4 @@
-import { initialize, getActorTestDir, runActor, expect, skipTest } from '../tools.mjs';
-
-// The actor spins up an HTTP server on 127.0.0.1; that works inside the
-// in-process LOCAL/MEMORY worker but is unreachable from the Apify platform
-// container, so the run never finishes. Base-href handling is pure parsing
-// logic in @crawlee/utils that doesn't depend on the storage backend, so
-// LOCAL+MEMORY coverage is sufficient.
-if (process.env.STORAGE_IMPLEMENTATION === 'PLATFORM') {
- await skipTest('localhost fixture is not reachable from the Apify platform');
-}
+import { initialize, getActorTestDir, runActor, expect } from '../tools.mjs';
const testActorDirname = getActorTestDir(import.meta.url);
await initialize(testActorDirname);
diff --git a/test/e2e/cheerio-robots-file/actor/main.js b/test/e2e/cheerio-robots-file/actor/main.js
index c24a56e94..266ee1977 100644
--- a/test/e2e/cheerio-robots-file/actor/main.js
+++ b/test/e2e/cheerio-robots-file/actor/main.js
@@ -1,7 +1,48 @@
+import http from 'node:http';
+
import { CheerioCrawler } from '@crawlee/cheerio';
-import { Browser, ImpitHttpClient } from '@crawlee/impit-client';
import { Actor } from 'apify';
+// Self-contained fixture: robots.txt disallows /cart and /checkout, and the
+// start page links to /cart alongside the allowed /collections/* pages. The
+// crawler may only reach the collections.
+const pages = {
+ '/robots.txt': ['User-agent: *', 'Disallow: /cart', 'Disallow: /checkout', ''].join('\n'),
+ '/': `<!doctype html>
+<html><head><title>Store</title></head>
+<body>
+ <a href="/cart">Cart</a>
+ <a href="/collections/audio">Audio</a>
+ <a href="/collections/tv">TV</a>
+</body></html>`,
+ // Every collection links back to /cart, so the robots.txt rule is what keeps
+ // it out of the dataset rather than a shortage of links to follow.
+ '/collections/audio': `<!doctype html>
+<html><head><title>Audio</title></head>
+<body><a href="/cart">Cart</a> <a href="/">Home</a></body></html>`,
+ '/collections/tv': `<!doctype html>
+<html><head><title>TV</title></head>
+<body><a href="/cart">Cart</a> <a href="/">Home</a></body></html>`,
+ '/cart': '<!doctype html><html><head><title>Cart</title></head><body>Cart</body></html>',
+ '/checkout': '<!doctype html><html><head><title>Checkout</title></head><body>Checkout</body></html>',
+};
+
+const server = http.createServer((req, res) => {
+ const body = pages[req.url];
+ if (body === undefined) {
+ res.statusCode = 404;
+ res.end('Not Found');
+ return;
+ }
+ const type = req.url === '/robots.txt' ? 'text/plain' : 'text/html';
+ res.writeHead(200, { 'content-type': `${type}; charset=utf-8` });
+ res.end(body);
+});
+
+await new Promise((resolve) => server.listen(0, '127.0.0.1', resolve));
+const { port } = server.address();
+const baseUrl = `http://127.0.0.1:${port}`;
+
await Actor.init({
storage:
process.env.STORAGE_IMPLEMENTATION === 'LOCAL'
@@ -10,9 +51,6 @@ await Actor.init({
});
const crawler = new CheerioCrawler({
- proxyConfiguration: await Actor.createProxyConfiguration(),
- // The store 429s plain HTTP clients; impersonating a browser gets us through.
- httpClient: new ImpitHttpClient({ browser: Browser.Firefox }),
maxRequestsPerCrawl: 10,
respectRobotsTxtFile: true,
});
@@ -27,11 +65,13 @@ crawler.router.addDefaultHandler(async ({ log, request, enqueueLinks, pushData }
});
await crawler.run([
- 'https://warehouse-theme-metal.myshopify.com',
- 'https://warehouse-theme-metal.myshopify.com/checkout', // '/checkout' is disallowed by robots.txt
+ baseUrl,
+ `${baseUrl}/checkout`, // '/checkout' is disallowed by robots.txt
]);
const data = await crawler.getData();
console.table(data.items);
+server.close();
+
await Actor.exit({ exit: Actor.isAtHome() });
diff --git a/test/e2e/cheerio-robots-file/actor/package.json b/test/e2e/cheerio-robots-file/actor/package.json
index 32ff9de44..e101f7a74 100644
--- a/test/e2e/cheerio-robots-file/actor/package.json
+++ b/test/e2e/cheerio-robots-file/actor/package.json
@@ -11,7 +11,6 @@
"@crawlee/core": "file:./packages/core",
"@crawlee/memory-storage": "file:./packages/memory-storage",
"@crawlee/cheerio": "file:./packages/cheerio-crawler",
- "@crawlee/impit-client": "file:./packages/impit-client",
"@crawlee/types": "file:./packages/types",
"@crawlee/utils": "file:./packages/utils"
},
diff --git a/test/e2e/cheerio-robots-file/test.mjs b/test/e2e/cheerio-robots-file/test.mjs
index a607b32bb..fb8794771 100644
--- a/test/e2e/cheerio-robots-file/test.mjs
+++ b/test/e2e/cheerio-robots-file/test.mjs
@@ -7,10 +7,7 @@ const { stats, datasetItems } = await runActor(testActorDirname);
await expect(stats.requestsFinished >= 1, 'All requests finished');
-const cartRequest = datasetItems.find((item) => item.url === 'https://warehouse-theme-metal.myshopify.com/cart');
-const checkoutRequest = datasetItems.find(
- (item) => item.url === 'https://warehouse-theme-metal.myshopify.com/checkout',
-);
+const paths = datasetItems.map((item) => new URL(item.url).pathname);
-await expect(!cartRequest, '/cart URL is not processed');
-await expect(!checkoutRequest, '/checkout URL is not processed');
+await expect(!paths.includes('/cart'), '/cart URL is not processed');
+await expect(!paths.includes('/checkout'), '/checkout URL is not processed');
diff --git a/test/e2e/playwright-enqueue-links-base/test.mjs b/test/e2e/playwright-enqueue-links-base/test.mjs
index 448973a3e..1af2a7738 100644
--- a/test/e2e/playwright-enqueue-links-base/test.mjs
+++ b/test/e2e/playwright-enqueue-links-base/test.mjs
@@ -1,13 +1,4 @@
-import { initialize, getActorTestDir, runActor, expect, skipTest } from '../tools.mjs';
-
-// The actor spins up an HTTP server on 127.0.0.1; that works inside the
-// in-process LOCAL/MEMORY worker but is unreachable from the Apify platform
-// container, so the run never finishes. Base-href handling is pure parsing
-// logic in @crawlee/utils that doesn't depend on the storage backend, so
-// LOCAL+MEMORY coverage is sufficient.
-if (process.env.STORAGE_IMPLEMENTATION === 'PLATFORM') {
- await skipTest('localhost fixture is not reachable from the Apify platform');
-}
+import { initialize, getActorTestDir, runActor, expect } from '../tools.mjs';
const testActorDirname = getActorTestDir(import.meta.url);
await initialize(testActorDirname);
diff --git a/test/e2e/playwright-introduction-guide/actor/main.js b/test/e2e/playwright-introduction-guide/actor/main.js
index f6cbd281f..a6fc346bf 100644
--- a/test/e2e/playwright-introduction-guide/actor/main.js
+++ b/test/e2e/playwright-introduction-guide/actor/main.js
@@ -89,8 +89,12 @@ router.addDefaultHandler(async ({ request, page, enqueueLinks, log }) => {
});
const crawler = new PlaywrightCrawler({
- // The store rate-limits the platform's shared egress IP, so crawl through a proxy.
- proxyConfiguration: await Actor.createProxyConfiguration(),
+ // The store 429s the platform's egress IP, direct or through the datacenter
+ // proxy pool; residential gets through. GitHub runners reach it directly, so
+ // they stay off the proxy and don't burn residential traffic.
+ proxyConfiguration: Actor.isAtHome()
+ ? await Actor.createProxyConfiguration({ groups: ['RESIDENTIAL'] })
+ : undefined,
maxRequestsPerCrawl: 15, // so the test runs faster
// Instead of the long requestHandler with
// if clauses we provide a router instance.
diff --git a/test/e2e/playwright-robots-file/actor/main.js b/test/e2e/playwright-robots-file/actor/main.js
index c50ba6939..f0b5c3385 100644
--- a/test/e2e/playwright-robots-file/actor/main.js
+++ b/test/e2e/playwright-robots-file/actor/main.js
@@ -1,6 +1,48 @@
+import http from 'node:http';
+
import { PlaywrightCrawler } from '@crawlee/playwright';
import { Actor } from 'apify';
+// Self-contained fixture: robots.txt disallows /cart and /checkout, and the
+// start page links to /cart alongside the allowed /collections/* pages. The
+// crawler may only reach the collections.
+const pages = {
+ '/robots.txt': ['User-agent: *', 'Disallow: /cart', 'Disallow: /checkout', ''].join('\n'),
+ '/': `<!doctype html>
+<html><head><title>Store</title></head>
+<body>
+ <a href="/cart">Cart</a>
+ <a href="/collections/audio">Audio</a>
+ <a href="/collections/tv">TV</a>
+</body></html>`,
+ // Every collection links back to /cart, so the robots.txt rule is what keeps
+ // it out of the dataset rather than a shortage of links to follow.
+ '/collections/audio': `<!doctype html>
+<html><head><title>Audio</title></head>
+<body><a href="/cart">Cart</a> <a href="/">Home</a></body></html>`,
+ '/collections/tv': `<!doctype html>
+<html><head><title>TV</title></head>
+<body><a href="/cart">Cart</a> <a href="/">Home</a></body></html>`,
+ '/cart': '<!doctype html><html><head><title>Cart</title></head><body>Cart</body></html>',
+ '/checkout': '<!doctype html><html><head><title>Checkout</title></head><body>Checkout</body></html>',
+};
+
+const server = http.createServer((req, res) => {
+ const body = pages[req.url];
+ if (body === undefined) {
+ res.statusCode = 404;
+ res.end('Not Found');
+ return;
+ }
+ const type = req.url === '/robots.txt' ? 'text/plain' : 'text/html';
+ res.writeHead(200, { 'content-type': `${type}; charset=utf-8` });
+ res.end(body);
+});
+
+await new Promise((resolve) => server.listen(0, '127.0.0.1', resolve));
+const { port } = server.address();
+const baseUrl = `http://127.0.0.1:${port}`;
+
await Actor.init({
storage:
process.env.STORAGE_IMPLEMENTATION === 'LOCAL'
@@ -9,8 +51,6 @@ await Actor.init({
});
const crawler = new PlaywrightCrawler({
- // The store rate-limits the platform's shared egress IP, so crawl through a proxy.
- proxyConfiguration: await Actor.createProxyConfiguration(),
maxRequestsPerCrawl: 10,
respectRobotsTxtFile: true,
});
@@ -25,11 +65,13 @@ crawler.router.addDefaultHandler(async ({ log, request, enqueueLinks, pushData }
});
await crawler.run([
- 'https://warehouse-theme-metal.myshopify.com',
- 'https://warehouse-theme-metal.myshopify.com/checkout', // '/checkout' is disallowed by robots.txt
+ baseUrl,
+ `${baseUrl}/checkout`, // '/checkout' is disallowed by robots.txt
]);
const data = await crawler.getData();
console.table(data.items);
+server.close();
+
await Actor.exit({ exit: Actor.isAtHome() });
diff --git a/test/e2e/playwright-robots-file/test.mjs b/test/e2e/playwright-robots-file/test.mjs
index 3eb38625d..4876022e8 100644
--- a/test/e2e/playwright-robots-file/test.mjs
+++ b/test/e2e/playwright-robots-file/test.mjs
@@ -7,10 +7,7 @@ const { stats, datasetItems } = await runActor(testActorDirname, 16384);
await expect(stats.requestsFinished >= 1, 'All requests finished');
-const cartRequest = datasetItems.find((item) => item.url === 'https://warehouse-theme-metal.myshopify.com/cart');
-const checkoutRequest = datasetItems.find(
- (item) => item.url === 'https://warehouse-theme-metal.myshopify.com/checkout',
-);
+const paths = datasetItems.map((item) => new URL(item.url).pathname);
-await expect(!cartRequest, '/cart URL is not processed');
-await expect(!checkoutRequest, '/checkout URL is not processed');
+await expect(!paths.includes('/cart'), '/cart URL is not processed');
+await expect(!paths.includes('/checkout'), '/checkout URL is not processed');
diff --git a/test/e2e/puppeteer-store-pagination-jquery/actor/main.js b/test/e2e/puppeteer-store-pagination-jquery/actor/main.js
index c78ef8241..f52136894 100644
--- a/test/e2e/puppeteer-store-pagination-jquery/actor/main.js
+++ b/test/e2e/puppeteer-store-pagination-jquery/actor/main.js
@@ -1,6 +1,69 @@
+import http from 'node:http';
+
import { Actor } from 'apify';
import { Dataset, PuppeteerCrawler } from '@crawlee/puppeteer';
+// Self-contained fixture: three paginated listing pages, each linking to
+// product detail pages, using the class names the crawler selects on.
+const PAGE_SIZE = 6;
+const PAGE_COUNT = 3;
+const MANUFACTURERS = ['sony', 'denon', 'sennheiser', 'yamaha', 'pioneer', 'klipsch'];
+
+const products = Array.from({ length: PAGE_SIZE * PAGE_COUNT }, (_, i) => ({
+ slug: `${MANUFACTURERS[i % MANUFACTURERS.length]}-model-${i + 1}`,
+ title: `Model ${i + 1}`,
+ sku: `SKU-${100 + i}`,
+ // Thousands separator so the handler's comma stripping is exercised.
+ price: `$${(1000 + i * 10).toLocaleString('en-US')}.00`,
+ inStock: i % 3 !== 0,
+}));
+
+const listingPage = (pageNo) => `<!doctype html>
+<html><head><title>All TVs, page ${pageNo}</title></head>
+<body>
+ ${products
+ .slice((pageNo - 1) * PAGE_SIZE, pageNo * PAGE_SIZE)
+ .map((p) => `<a class="product-item__image-wrapper" href="/products/${p.slug}">${p.title}</a>`)
+ .join('\n ')}
+ ${pageNo < PAGE_COUNT ? `<a class="pagination__next" href="/collections/all-tvs?page=${pageNo + 1}">Next</a>` : ''}
+</body></html>`;
+
+const detailPage = (product) => `<!doctype html>
+<html><head><title>${product.title}</title></head>
+<body>
+ <div class="product-meta"><h1>${product.title}</h1></div>
+ <span class="product-meta__sku-number">${product.sku}</span>
+ <span class="price">${product.price}</span>
+ <span class="price">Regular price</span>
+ <span class="product-form__inventory">${product.inStock ? 'In stock' : 'Out of stock'}</span>
+</body></html>`;
+
+const server = http.createServer((req, res) => {
+ const { pathname, searchParams } = new URL(req.url, 'http://127.0.0.1');
+ let body;
+
+ if (pathname === '/collections/all-tvs') {
+ const pageNo = Number(searchParams.get('page') ?? 1);
+ if (pageNo >= 1 && pageNo <= PAGE_COUNT) body = listingPage(pageNo);
+ } else if (pathname.startsWith('/products/')) {
+ const product = products.find((p) => p.slug === pathname.slice('/products/'.length));
+ if (product) body = detailPage(product);
+ }
+
+ if (body === undefined) {
+ res.statusCode = 404;
+ res.end('Not Found');
+ return;
+ }
+
+ res.writeHead(200, { 'content-type': 'text/html; charset=utf-8' });
+ res.end(body);
+});
+
+await new Promise((resolve) => server.listen(0, '127.0.0.1', resolve));
+const { port } = server.address();
+const baseUrl = `http://127.0.0.1:${port}`;
+
const mainOptions = {
exit: Actor.isAtHome(),
storage:
@@ -11,14 +74,9 @@ const mainOptions = {
await Actor.main(async () => {
const crawler = new PuppeteerCrawler({
- // The store rate-limits the platform's shared egress IP, so crawl through a proxy.
- proxyConfiguration: await Actor.createProxyConfiguration(),
maxRequestsPerCrawl: 10,
preNavigationHooks: [
- async ({ page }, goToOptions) => {
- await page.evaluateOnNewDocument(() => {
- localStorage.setItem('themeExitPopup', 'true');
- });
+ (_crawlingContext, goToOptions) => {
goToOptions.waitUntil = ['networkidle2'];
},
],
@@ -31,7 +89,7 @@ await Actor.main(async () => {
if (label === 'START') {
log.info('Store opened');
const nextButtonSelector = '.pagination__next';
- // enqueue product details from the first three pages of the store
+ // enqueue product details from the first two pages of the store
for (let pageNo = 1; pageNo < 3; pageNo++) {
// Wait for network events to finish
await page.waitForNetworkIdle({ concurrency: 2 });
@@ -39,7 +97,7 @@ await Actor.main(async () => {
await enqueueLinks({
selector: 'a.product-item__image-wrapper',
label: 'DETAIL',
- globs: ['https://warehouse-theme-metal.myshopify.com/*/*'],
+ globs: [`${baseUrl}/*/*`],
});
log.info(`Enqueued actors for page ${pageNo}`);
log.info('Loading the next page');
@@ -48,8 +106,8 @@ await Actor.main(async () => {
} else if (label === 'DETAIL') {
log.info(`Scraping ${url}`);
await injectJQuery();
- const urlPart = url.split('/').slice(-1); // ['sennheiser-mke-440-professional-stereo-shotgun-microphone-mke-440']
- const manufacturer = urlPart[0].split('-')[0]; // 'sennheiser'
+ const urlPart = url.split('/').slice(-1); // ['sony-model-1']
+ const manufacturer = urlPart[0].split('-')[0]; // 'sony'
/* eslint-disable no-undef */
const results = await page.evaluate(() => {
@@ -81,7 +139,7 @@ await Actor.main(async () => {
},
});
- await crawler.run([
- { url: 'https://warehouse-theme-metal.myshopify.com/collections/all-tvs', userData: { label: 'START' } },
- ]);
+ await crawler.run([{ url: `${baseUrl}/collections/all-tvs`, userData: { label: 'START' } }]);
}, mainOptions);
+
+server.close();
diff --git a/test/e2e/puppeteer-store-pagination-jquery/test.mjs b/test/e2e/puppeteer-store-pagination-jquery/test.mjs
index 8f87841e7..06670dd93 100644
--- a/test/e2e/puppeteer-store-pagination-jquery/test.mjs
+++ b/test/e2e/puppeteer-store-pagination-jquery/test.mjs
@@ -8,6 +8,12 @@ const { stats, datasetItems } = await runActor(testActorDirname, 16384);
await expect(stats.requestsFinished >= 10, 'All requests finished');
await expect(datasetItems.length > 5 && datasetItems.length < 15, 'Number of dataset items');
await expect(
- validateDataset(datasetItems, ['url', 'manufacturer', 'title', 'sku', 'currentPrice', 'availableInStock']),
+ validateDataset(datasetItems, ['manufacturer', 'title', 'sku', 'currentPrice', 'availableInStock']),
'Dataset items validation',
);
+// `url` is checked separately: validateDataset matches it against a regex that
+// rejects the fixture's 127.0.0.1 origin.
+await expect(
+ datasetItems.every((item) => URL.canParse(item.url) && new URL(item.url).pathname.startsWith('/products/')),
+ 'Dataset items have product URLs',
+);
diff --git a/test/e2e/puppeteer-store-pagination/actor/main.js b/test/e2e/puppeteer-store-pagination/actor/main.js
index c9e1b0da7..9c609ae4a 100644
--- a/test/e2e/puppeteer-store-pagination/actor/main.js
+++ b/test/e2e/puppeteer-store-pagination/actor/main.js
@@ -1,6 +1,69 @@
+import http from 'node:http';
+
import { Actor } from 'apify';
import { Dataset, PuppeteerCrawler } from '@crawlee/puppeteer';
+// Self-contained fixture: three paginated listing pages, each linking to
+// product detail pages, using the class names the crawler selects on.
+const PAGE_SIZE = 6;
+const PAGE_COUNT = 3;
+const MANUFACTURERS = ['sony', 'denon', 'sennheiser', 'yamaha', 'pioneer', 'klipsch'];
+
+const products = Array.from({ length: PAGE_SIZE * PAGE_COUNT }, (_, i) => ({
+ slug: `${MANUFACTURERS[i % MANUFACTURERS.length]}-model-${i + 1}`,
+ title: `Model ${i + 1}`,
+ sku: `SKU-${100 + i}`,
+ // Thousands separator so the handler's comma stripping is exercised.
+ price: `$${(1000 + i * 10).toLocaleString('en-US')}.00`,
+ inStock: i % 3 !== 0,
+}));
+
+const listingPage = (pageNo) => `<!doctype html>
+<html><head><title>All TVs, page ${pageNo}</title></head>
+<body>
+ ${products
+ .slice((pageNo - 1) * PAGE_SIZE, pageNo * PAGE_SIZE)
+ .map((p) => `<a class="product-item__image-wrapper" href="/products/${p.slug}">${p.title}</a>`)
+ .join('\n ')}
+ ${pageNo < PAGE_COUNT ? `<a class="pagination__next" href="/collections/all-tvs?page=${pageNo + 1}">Next</a>` : ''}
+</body></html>`;
+
+const detailPage = (product) => `<!doctype html>
+<html><head><title>${product.title}</title></head>
+<body>
+ <div class="product-meta"><h1>${product.title}</h1></div>
+ <span class="product-meta__sku-number">${product.sku}</span>
+ <span class="price">${product.price}</span>
+ <span class="price">Regular price</span>
+ <span class="product-form__inventory">${product.inStock ? 'In stock' : 'Out of stock'}</span>
+</body></html>`;
+
+const server = http.createServer((req, res) => {
+ const { pathname, searchParams } = new URL(req.url, 'http://127.0.0.1');
+ let body;
+
+ if (pathname === '/collections/all-tvs') {
+ const pageNo = Number(searchParams.get('page') ?? 1);
+ if (pageNo >= 1 && pageNo <= PAGE_COUNT) body = listingPage(pageNo);
+ } else if (pathname.startsWith('/products/')) {
+ const product = products.find((p) => p.slug === pathname.slice('/products/'.length));
+ if (product) body = detailPage(product);
+ }
+
+ if (body === undefined) {
+ res.statusCode = 404;
+ res.end('Not Found');
+ return;
+ }
+
+ res.writeHead(200, { 'content-type': 'text/html; charset=utf-8' });
+ res.end(body);
+});
+
+await new Promise((resolve) => server.listen(0, '127.0.0.1', resolve));
+const { port } = server.address();
+const baseUrl = `http://127.0.0.1:${port}`;
+
await Actor.init({
storage:
process.env.STORAGE_IMPLEMENTATION === 'LOCAL'
@@ -9,14 +72,9 @@ await Actor.init({
});
const crawler = new PuppeteerCrawler({
- // The store rate-limits the platform's shared egress IP, so crawl through a proxy.
- proxyConfiguration: await Actor.createProxyConfiguration(),
maxRequestsPerCrawl: 10,
preNavigationHooks: [
- async ({ page }, goToOptions) => {
- await page.evaluateOnNewDocument(() => {
- localStorage.setItem('themeExitPopup', 'true');
- });
+ (_crawlingContext, goToOptions) => {
goToOptions.waitUntil = ['networkidle2'];
},
],
@@ -25,7 +83,7 @@ const crawler = new PuppeteerCrawler({
crawler.router.addHandler('START', async ({ log, enqueueLinks, page }) => {
log.info('Store opened');
const nextButtonSelector = '.pagination__next';
- // enqueue product details from the first three pages of the store
+ // enqueue product details from the first two pages of the store
for (let pageNo = 1; pageNo < 3; pageNo++) {
// Wait for network events to finish
await page.waitForNetworkIdle({ concurrency: 2 });
@@ -33,7 +91,7 @@ crawler.router.addHandler('START', async ({ log, enqueueLinks, page }) => {
await enqueueLinks({
selector: 'a.product-item__image-wrapper',
label: 'DETAIL',
- globs: ['https://warehouse-theme-metal.myshopify.com/*/*'],
+ globs: [`${baseUrl}/*/*`],
});
log.info(`Enqueued actors for page ${pageNo}`);
log.info('Loading the next page');
@@ -44,8 +102,8 @@ crawler.router.addHandler('START', async ({ log, enqueueLinks, page }) => {
crawler.router.addHandler('DETAIL', async ({ log, page, request: { url } }) => {
log.info(`Scraping ${url}`);
- const urlPart = url.split('/').slice(-1); // ['sennheiser-mke-440-professional-stereo-shotgun-microphone-mke-440']
- const manufacturer = urlPart[0].split('-')[0]; // 'sennheiser'
+ const urlPart = url.split('/').slice(-1); // ['sony-model-1']
+ const manufacturer = urlPart[0].split('-')[0]; // 'sony'
const title = await page
.locator('.product-meta h1')
@@ -80,8 +138,8 @@ crawler.router.addHandler('DETAIL', async ({ log, page, request: { url } }) => {
await Dataset.pushData(results);
});
-await crawler.run([
- { url: 'https://warehouse-theme-metal.myshopify.com/collections/all-tvs', userData: { label: 'START' } },
-]);
+await crawler.run([{ url: `${baseUrl}/collections/all-tvs`, userData: { label: 'START' } }]);
+
+server.close();
await Actor.exit({ exit: Actor.isAtHome() });
diff --git a/test/e2e/puppeteer-store-pagination/test.mjs b/test/e2e/puppeteer-store-pagination/test.mjs
index 8f87841e7..06670dd93 100644
--- a/test/e2e/puppeteer-store-pagination/test.mjs
+++ b/test/e2e/puppeteer-store-pagination/test.mjs
@@ -8,6 +8,12 @@ const { stats, datasetItems } = await runActor(testActorDirname, 16384);
await expect(stats.requestsFinished >= 10, 'All requests finished');
await expect(datasetItems.length > 5 && datasetItems.length < 15, 'Number of dataset items');
await expect(
- validateDataset(datasetItems, ['url', 'manufacturer', 'title', 'sku', 'currentPrice', 'availableInStock']),
+ validateDataset(datasetItems, ['manufacturer', 'title', 'sku', 'currentPrice', 'availableInStock']),
'Dataset items validation',
);
+// `url` is checked separately: validateDataset matches it against a regex that
+// rejects the fixture's 127.0.0.1 origin.
+await expect(
+ datasetItems.every((item) => URL.canParse(item.url) && new URL(item.url).pathname.startsWith('/products/')),
+ 'Dataset items have product URLs',
+);
diff --git a/test/e2e/tools.mjs b/test/e2e/tools.mjs
index c47615d26..8ba4899d2 100644
--- a/test/e2e/tools.mjs
+++ b/test/e2e/tools.mjs
@@ -21,9 +21,16 @@ function execSync(command, options) {
}
/**
+ * The index is not always 0: AdaptivePlaywrightCrawler discards the Statistics
+ * the base crawler created and installs its own, which lands on the next id.
* @param {string} name
*/
-const isPrivateEntry = (name) => name === 'SDK_CRAWLER_STATISTICS_0' || name === 'SDK_SESSION_POOL_STATE';
+const isCrawlerStatisticsKey = (name) => name.startsWith('SDK_CRAWLER_STATISTICS_');
+
+/**
+ * @param {string} name
+ */
+const isPrivateEntry = (name) => isCrawlerStatisticsKey(name) || name === 'SDK_SESSION_POOL_STATE';
export const SKIPPED_TEST_CLOSE_CODE = 404;
@@ -49,14 +56,19 @@ export function getStorage(dirName) {
* @param {string} dirName
*/
export async function getStats(dirName) {
- const dir = getStorage(dirName);
- const path = join(dir, `key_value_stores/default/SDK_CRAWLER_STATISTICS_0.json`);
+ const dir = join(getStorage(dirName), 'key_value_stores/default');
+
+ if (!existsSync(dir)) {
+ return false;
+ }
+
+ const [statsFile] = (await readdir(dir)).filter((name) => isCrawlerStatisticsKey(name)).sort();
- if (!existsSync(path)) {
+ if (!statsFile) {
return false;
}
- return fs.readJSON(path);
+ return fs.readJSON(join(dir, statsFile));
}
/**
@@ -217,7 +229,12 @@ export async function runActor(dirName, memory = 4096) {
const runTook = (runFinishedAt.getTime() - runStartedAt.getTime()) / 1000;
console.log(`[run] View run: https://console.apify.com/view/runs/${runId} [run took ${runTook}s]`);
- const statsRecord = await client.keyValueStore(defaultKeyValueStoreId).getRecord('SDK_CRAWLER_STATISTICS_0');
+ const { items: kvKeys } = await client.keyValueStore(defaultKeyValueStoreId).listKeys();
+ const [statsKey] = kvKeys
+ .map(({ key }) => key)
+ .filter((key) => isCrawlerStatisticsKey(key))
+ .sort();
+ const statsRecord = statsKey && (await client.keyValueStore(defaultKeyValueStoreId).getRecord(statsKey));
stats = statsRecord?.value;
const { items } = await client.dataset(defaultDatasetId).listItems();