To achieve your goal of handling a JavaScript CAPTCHA, saving the cookie, and using it with the BasicCrawler, you can follow these steps:
Plan
- Use a browser-based crawler to solve the CAPTCHA: Since the CAPTCHA is JavaScript-based, you need a browser environment (via
PlaywrightCrawler or PuppeteerCrawler) to open the page and solve it.
- Save the CAPTCHA cookie: Once the CAPTCHA is solved, extract the cookie and store it.
- Configure
BasicCrawler to use the cookie: Use the saved cookie in the headers for API requests made by BasicCrawler.
Implementation
1. Solve the CAPTCHA and Save the Cookie
Use PlaywrightCrawler or PuppeteerCrawler to load the CAPTCHA page, solve it, and extract the required cookie.
import { PlaywrightCrawler, KeyValueStore } from 'crawlee';
const captchaSolver = new PlaywrightCrawler({
async requestHandler({ page, log }) {
log.info(`Solving CAPTCHA on ${page.url()}`);
// Wait for the CAPTCHA to be solved (e.g., user interaction or automation)
// This might involve manually solving it or using an external service.
await page.waitForSelector('#captcha-solved-element'); // Adjust based on your CAPTCHA implementation.
// Extract cookies after solving the CAPTCHA
const cookies = await page.context().cookies();
const targetCookie = cookies.find(cookie => cookie.name === 'target_captcha_cookie');
if (targetCookie) {
log.info('CAPTCHA solved, saving cookie...');
await KeyValueStore.setValue('captcha_cookie', targetCookie);
} else {
log.error('Failed to retrieve CAPTCHA cookie.');
}
},
});
// Run the CAPTCHA solver with the page where the CAPTCHA appears
await captchaSolver.run(['https://example.com/captcha-page']);
2. Use the Cookie in BasicCrawler for API Requests
Retrieve the saved cookie and include it in the headers for requests made by BasicCrawler.
import { BasicCrawler, KeyValueStore } from 'crawlee';
const cookie = await KeyValueStore.getValue('captcha_cookie');
if (!cookie) {
throw new Error('CAPTCHA cookie not found. Solve the CAPTCHA first.');
}
// Create a crawler that uses the cookie in its requests
const apiCrawler = new BasicCrawler({
async requestHandler({ request, sendRequest, log }) {
log.info(`Sending request to ${request.url}`);
// Include the cookie in the request headers
const response = await sendRequest({
url: request.url,
headers: {
Cookie: `${cookie.name}=${cookie.value}`,
},
});
log.info(`Response status: ${response.statusCode}`);
},
});
// Run the crawler on the target API
await apiCrawler.run([
'https://example.com/api/endpoint1',
'https://example.com/api/endpoint2',
]);
3. Handle CAPTCHA Responses Dynamically
If the API responds with a CAPTCHA challenge (e.g., HTTP 403 or a specific JSON response), redirect the crawler back to the CAPTCHA-solving process and resume the API requests.
import { BasicCrawler, KeyValueStore } from 'crawlee';
const apiCrawler = new BasicCrawler({
async requestHandler({ request, sendRequest, log }) {
try {
log.info(`Sending request to ${request.url}`);
const cookie = await KeyValueStore.getValue('captcha_cookie');
const response = await sendRequest({
url: request.url,
headers: {
Cookie: `${cookie.name}=${cookie.value}`,
},
});
// Check for CAPTCHA challenge in the response
if (response.statusCode === 403 || response.body.includes('captcha')) {
log.warn(`CAPTCHA detected on ${request.url}, solving it...`);
// Redirect to CAPTCHA solving
const captchaSolver = new PlaywrightCrawler({
async requestHandler({ page, log }) {
log.info(`Solving CAPTCHA on ${page.url()}`);
await page.waitForSelector('#captcha-solved-element'); // Adjust selector
const cookies = await page.context().cookies();
const targetCookie = cookies.find(cookie => cookie.name === 'target_captcha_cookie');
if (targetCookie) {
log.info('CAPTCHA solved, updating cookie...');
await KeyValueStore.setValue('captcha_cookie', targetCookie);
} else {
throw new Error('Failed to retrieve CAPTCHA cookie.');
}
},
});
await captchaSolver.run([request.url]);
log.info('Resuming API requests...');
} else {
log.info(`Response status: ${response.statusCode}`);
}
} catch (error) {
log.error(`Failed to process ${request.url}: ${error.message}`);
}
},
});
// Run the crawler on the target API
await apiCrawler.run([
'https://example.com/api/endpoint1',
'https://example.com/api/endpoint2',
]);
Key Points
- CAPTCHA Handling:
- Use
PlaywrightCrawler or PuppeteerCrawler to handle JavaScript-based CAPTCHAs.
- Ensure the CAPTCHA page is fully loaded and solved before extracting cookies.
- Cookie Storage:
- Use
KeyValueStore for storing and retrieving cookies between crawlers.
- Dynamic CAPTCHA Detection:
- Monitor API responses for CAPTCHA challenges and redirect to CAPTCHA-solving logic as needed.
This approach ensures that your BasicCrawler is equipped to handle CAPTCHA challenges dynamically while efficiently making requests to the API.