When a certain response is received, pause the crawler, change the cookies and resume the crawler (and retry the sibling requests). You will verify that the condition matches in postNavigationHooks. You will use async-mutex to ensure that it is called only once and the cookies are set only once (because the crawler is multi-threaded and execute requests concurrently)
Assistant
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
To achieve the goal of pausing the crawler upon receiving a specific response, modifying cookies, and resuming the crawler (while ensuring this operation happens only once using async-mutex), follow these steps:
Steps to Implement
Initialize the Crawler with a postNavigationHook
Use the postNavigationHooks option to check for the specific response condition after navigation.
Use async-mutex to ensure the cookie modification and crawler pause/resume logic is executed only once.
Pause the Crawler
Use the crawler.autoscaledPool.pause() method to pause the crawler.
Modify Cookies
Adjust the cookies for the session or globally, depending on your needs.
Retry Sibling Requests
Restart the crawler and retry the sibling requests.
Use async-mutex for Thread Safety
Prevent the cookie modification logic from being executed multiple times by concurrent threads.
Code Example
Below is a complete example using HttpCrawler (you can adapt it for other crawlers, such as CheerioCrawler, PlaywrightCrawler, or PuppeteerCrawler, by tweaking the logic).
typescript
import { HttpCrawler } from '@crawlee/http';
import { Mutex } from 'async-mutex';
const mutex = new Mutex(); // Ensure critical section is executed only once
const crawler = new HttpCrawler({
maxConcurrency: 10, // Example concurrency
navigationTimeoutSecs: 30, // Timeout for requests
// Pre-navigation hooks (optional)
preNavigationHooks: [
async (crawlingContext, gotOptions) => {
// Optionally modify the request (e.g., headers, cookies) before navigation
},
],
// Post-navigation hooks
postNavigationHooks: [
async (crawlingContext) => {
const { response, session, log } = crawlingContext;
// Check the response status or content for your specific condition
if (response.statusCode === 403 || response.body.includes('Blocked')) {
log.info('Condition matched, pausing the crawler and modifying cookies.');
// Use the mutex to ensure this block is executed only once
await mutex.runExclusive(async () => {
// Pause the crawler
await crawler.autoscaledPool.pause();
log.info('Crawler paused.');
// Modify session cookies (or global cookies, depending on your use case)
if (session) {
session.setCookie('key=value; Path=/; HttpOnly', 'https://example.com');
log.info('Cookies updated for the session.');
} else {
log.warning('Session is not available.');
}
// Resume the crawler
await crawler.autoscaledPool.resume();
log.info('Crawler resumed.');
});
}
},
],
async requestHandler({ request, log }) {
log.info(`Processing ${request.url}`);
// Your request handling logic here
},
async failedRequestHandler({ request, log }) {
log.error(`Request failed: ${request.url}`);
},
});
// Run the crawler with a list of URLs
await crawler.run([
'https://example.com/page1',
'https://example.com/page2',
'https://example.com/page3',
]);
Key Points
async-mutex Usage:
The Mutex ensures that the block of code for pausing, modifying cookies, and resuming the crawler is executed only once, even when multiple requests trigger the condition concurrently.
Pausing and Resuming:
crawler.autoscaledPool.pause() pauses the crawler, ensuring no new requests are processed.
crawler.autoscaledPool.resume() resumes the crawler after the cookies have been modified.
Session Management:
If sessions are enabled (useSessionPool: true), cookies can be modified per session using session.setCookie.
Retrying Requests:
Sibling requests will automatically retry based on the logic of the crawler once it resumes. No special handling is required unless you need custom retry logic.
Logging:
Add appropriate logging to ensure you can trace the execution of the critical section.
Adaptation for Other Crawlers
For PlaywrightCrawler or PuppeteerCrawler, you can inject cookies into the browser context using APIs like page.setCookie.
For CheerioCrawler, modify the Cookie header in the requestHandler or preNavigationHooks.
Dependencies
Ensure you have the async-mutex package installed:
bash
npm install async-mutex
This approach ensures thread-safe, scalable handling of the condition while maintaining crawler concurrency.