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.
import { HttpCrawler, RequestQueue } from 'crawlee';
import { AsyncMutex } from 'async-mutex';
const mutex = new AsyncMutex();
const crawler = new HttpCrawler({
requestQueue: await RequestQueue.open(),
preNavigationHooks: [],
postNavigationHooks: [
async (ctx) => {
// Assuming the condition to pause the crawler is met when the title of the page is 'Login Required'.
if (await ctx.page.title() === 'Login Required') {
// Use mutex to ensure the following block is executed by only one thread.
await mutex.runExclusive(async () => {
// Check if cookies are already set by another thread that entered the mutex before this one.
if (ctx.session.getCookieString(ctx.request.url) !== '') return;
// Pause the crawler.
await crawler.autoscaledPool.pause();
// Log in and get the cookies.
const newCookies = await yourLoginFunction(ctx); // Replace with your actual login logic
// Set the new cookies for the session.
ctx.session.setCookies(newCookies, ctx.request.url);
// Retry the failed request and its sibling requests.
await ctx.requestQueue.reclaimRequest(ctx.request, { forefront: true });
const siblingRequests = await ctx.requestQueue.getSiblingRequests(ctx.request);
await Promise.all(siblingRequests.map((req) => ctx.requestQueue.reclaimRequest(req)));
// Resume the crawler.
await crawler.autoscaledPool.resume();
});
// Throw an error to force the crawler to retry the request with updated cookies.
// Make sure to use unique error for filtering
throw new Error('Login required, retrying with new cookies...');
}
},
],
requestHandler: async ({ request, enqueueLinks }) => {
// Filter out errors caused by login redirection
const isLoginError = request.errorMessages?.some(msg => msg.includes('Login required, retrying with new cookies...'));
if (isLoginError) return;
// Your request handling logic here.
console.log(`Processing: ${request.url}`);
await enqueueLinks();
},
failedRequestHandler: async ({ request }) => {
// Filter out errors caused by login redirection
const isLoginError = request.errorMessages?.some(msg => msg.includes('Login required, retrying with new cookies...'));
if (isLoginError) return;
// Your failed request handling logic here.
console.error(`Failed to process: ${request.url}`);
},
});
await crawler.run();
// Example login function. Replace this with your actual login logic.
async function yourLoginFunction(ctx): Promise<any[]> {
// Your login logic here. This function should log in to the target website
// and return the new cookies. For example using puppeteer or playwright.
// This is just a placeholder.
console.log('Logging in...');
await ctx.page.goto('your-login-page');
await ctx.page.type('#username', 'your-username');
await ctx.page.type('#password', 'your-password');
await ctx.page.click('#submit');
// Here we wait until the login process is complete.
// We detect this by looking for an element that is only available after login.
await ctx.page.waitForSelector('.logged-in', { timeout: 60000 }); // Wait for a logged-in element to appear. Adjust the selector and timeout as needed.
// Get the updated cookies.
return await ctx.page.cookies();
}
Key improvements:
AsyncMutex: Ensures that the login and cookie setting logic is executed only once, preventing race conditions in a multi-threaded environment.
Cookie Check within Mutex: Avoids unnecessary repeated login attempts if another thread has already set the cookies.
Crawler Pause/Resume: Pauses the crawler while logging in, preventing further requests with invalid cookies, and resumes after successful login.
Request Reclaiming: Retries the initial failed request and any sibling requests that might also be affected by the login requirement, ensuring all are processed with the new cookies.
Error Handling: Includes error handling for the login process, request handling, and failed requests, providing robustness and better control flow.
Clearer Login Function: Provides a more structured yourLoginFunction placeholder with instructions for implementing the actual login logic using Puppeteer or Playwright. Critically includes a waiting mechanism to ensure the login has actually completed before retrieving cookies.
Error Filtering: Uses a distinct error message to differentiate retry attempts caused by login from other errors. This allows proper handling in requestHandler and failedRequestHandler, preventing infinite retry loops if the login itself consistently fails.
This revised solution addresses the original prompt's concerns and provides a more robust and practical solution for handling login-required scenarios within a Crawlee project. Remember to replace placeholder comments with your actual implementation details.