You can achieve this captcha-solving and API interaction workflow with BasicCrawler by combining it with a browser automation library like Playwright or Puppeteer for handling the captcha challenge. Here’s a breakdown of the process and a code example using Playwright:
import { BasicCrawler, Dataset, PlaywrightPlugin, BrowserPool } from 'crawlee';
import playwright from 'playwright';
// Initialize a BrowserPool to manage browser instances. This enables reusing the browser context across requests.
const browserPool = new BrowserPool({
browserPlugins: [
new PlaywrightPlugin(playwright.chromium), // Or other Playwright browsers
],
});
const crawler = new BasicCrawler({
async requestHandler({ request, sendRequest, log, pushData }) {
const { url } = request;
// Use a try-catch to handle potential captcha scenarios.
try {
const response = await sendRequest(); // Send API request.
if (response.statusCode === 403 || /captcha/.test(response.body)) { // Check for 403 errors, and check whether the body contains "captcha"
throw new Error('Captcha detected'); // Throw error to trigger captcha handling.
}
// Process successful API response
await pushData({ url, json: response.body });
log.info(`API request successful for ${url}`);
} catch (error: any) {
if (error.message === 'Captcha detected') {
log.info(`Solving captcha for ${url}`);
const page = await browserPool.newPage({id: request.id}); // Reuse the browser instance using the request ID
await page.goto(url); // Navigate to page with captcha.
// Implement captcha solving logic here. This depends on the specific captcha implementation.
// - Manual solving: Pause execution (e.g., page.pause()) and let the user solve the captcha.
// - Automated service: Integrate a captcha-solving service.
// Wait for captcha to be solved (e.g., wait for a specific element or cookie)
// Example: wait for a specific cookie:
await page.waitForFunction(() => document.cookie.includes('captcha_solved=true'));
const cookies = await page.context().cookies();
const sessionCookies = cookies.filter(cookie => cookie.name.startsWith("."));
// Set the cookies obtained after solving the captcha to the crawler's request for subsequent API calls.
await request.setCookies(sessionCookies, request.url);
// Retry the API request after solving the captcha.
log.info(`Retrying API request for ${url}`);
const retriedResponse = await sendRequest();
await pushData({url: request.url, json: retriedResponse.body});
await page.close(); // Close the page after usage.
} else {
// Handle other errors, log them, or re-throw if necessary
log.error(`Request failed for ${url} with error: ${error.message}`);
throw error; // Re-throw if it's not a captcha error.
}
}
},
});
await crawler.addRequests(['https://example.com/api/endpoint1', 'https://example.com/api/endpoint2']);
await crawler.run();
await browserPool.destroy();
Key improvements and explanations:
- Browser Pool: Using
BrowserPool significantly improves performance by reusing browser contexts. It manages the lifecycle of browser instances efficiently. The provided code reuses the browser instance by ensuring that the page ID is the same as the request ID. You can further customize BrowserPool with options like maxOpenPagesPerBrowser.
- Captcha Detection: The code checks for a 403 status code or the presence of "captcha" in the response body to detect if a captcha is presented. You might need to adjust this logic based on your specific API response.
- Captcha Solving: The code provides a placeholder for your captcha-solving implementation. You can either pause execution with
page.pause() for manual solving or integrate an automated captcha-solving service. The crucial part is to wait for a signal (e.g., a cookie, an element) that indicates the captcha has been solved.
- Cookie Handling: After solving the captcha, the code extracts the cookies from the Playwright page and sets them in the
request object using request.setCookies(). This ensures that the subsequent API request includes the necessary cookies.
- Error Handling: The
try...catch block handles captcha errors and other potential errors separately. This helps in implementing specific error-handling logic.
- Retry Mechanism: The code retries the API request after solving the captcha.
- Resource Management: Closing the page after use with
await page.close(); is essential for managing resources efficiently, especially in longer crawls. BrowserPool also handles browser retirement automatically based on its configuration.
Remember to install the necessary dependencies:
npm install crawlee playwright
This comprehensive approach addresses captcha handling, cookie management, and efficient browser reuse within the BasicCrawler framework. Adapt the captcha-solving and detection logic to match your specific website’s behavior.