Integrationen

Apify + CaptchaAI: Cloud-Scraping-Plattform-Integration

Apify ist eine Cloud-Scraping-Plattform, auf der Crawlee-Actors ausgeführt werden. So fügen Sie Ihren Apify-Actors die CAPTCHA-Lösung CaptchaAI hinzu.


Actor-Setup

Eingabeschema

{
    "title": "CAPTCHA Scraper Input",
    "type": "object",
    "properties": {
        "startUrls": {
            "title": "Start URLs",
            "type": "array",
            "editor": "requestListSources"
        },
        "captchaaiApiKey": {
            "title": "CaptchaAI API Key",
            "type": "string",
            "isSecret": true
        },
        "maxConcurrency": {
            "title": "Max Concurrency",
            "type": "integer",
            "default": 3
        }
    },
    "required": ["startUrls", "captchaaiApiKey"]
}

Actor-Code

const { Actor } = require('apify');
const { PlaywrightCrawler } = require('crawlee');

Actor.main(async () => {
    const input = await Actor.getInput();
    const { startUrls, captchaaiApiKey, maxConcurrency = 3 } = input;

    const solver = new CaptchaAISolver(captchaaiApiKey);

    const crawler = new PlaywrightCrawler({
        maxConcurrency,
        requestHandlerTimeoutSecs: 180,

        async requestHandler({ request, page, log }) {
            await page.goto(request.url, { waitUntil: 'networkidle' });

            // Check for CAPTCHA
            const sitekey = await page.evaluate(() => {
                const el = document.querySelector('[data-sitekey]');
                return el ? el.getAttribute('data-sitekey') : null;
            });

            if (sitekey) {
                log.info(`Solving CAPTCHA on ${request.url}`);
                const token = await solver.solve(sitekey, request.url);

                // Inject and submit
                await page.evaluate((t) => {
                    document.querySelector('[name="g-recaptcha-response"]').value = t;
                    const cb = document.querySelector('.g-recaptcha')?.getAttribute('data-callback');
                    if (cb && window[cb]) window[cb](t);
                }, token);

                await page.click('button[type="submit"]');
                await page.waitForNavigation({ timeout: 15000 });
            }

            // Extract data
            const title = await page.title();
            const items = await page.$$eval('.item', els =>
                els.map(el => ({
                    name: el.querySelector('.name')?.textContent?.trim(),
                    price: el.querySelector('.price')?.textContent?.trim(),
                    url: el.querySelector('a')?.href,
                }))
            );

            // Push to Apify dataset
            await Actor.pushData({
                url: request.url,
                title,
                items,
                scrapedAt: new Date().toISOString(),
            });

            log.info(`Scraped ${items.length} items from ${request.url}`);
        },
    });

    await crawler.run(startUrls);
});


class CaptchaAISolver {
    constructor(apiKey) {
        this.apiKey = apiKey;
    }

    async solve(sitekey, pageurl) {
        const params = new URLSearchParams({
            key: this.apiKey,
            method: 'userrecaptcha',
            googlekey: sitekey,
            pageurl: pageurl,
            json: '1',
        });

        const submitResp = await fetch('https://ocr.captchaai.com/in.php', {
            method: 'POST',
            body: params,
        });
        const submitResult = await submitResp.json();

        if (submitResult.status !== 1) {
            throw new Error(`Submit: ${submitResult.request}`);
        }

        const taskId = submitResult.request;
        await new Promise(r => setTimeout(r, 15000));

        for (let i = 0; i < 24; i++) {
            const pollResp = await fetch(
                `https://ocr.captchaai.com/res.php?key=${this.apiKey}&action=get&id=${taskId}&json=1`
            );
            const result = await pollResp.json();

            if (result.status === 1) return result.request;
            if (result.request !== 'CAPCHA_NOT_READY') {
                throw new Error(`Solve: ${result.request}`);
            }
            await new Promise(r => setTimeout(r, 5000));
        }

        throw new Error('Timeout');
    }
}

Umgebungsvariablen auf Apify

Bewahren Sie Ihren CaptchaAI-Schlüssel sicher auf:

  1. Gehen Sie zu Actor-Einstellungen → Umgebungsvariablen
  2. Hinzufügen: CAPTCHAAI_API_KEY = Ihr Schlüssel (als geheim markieren)
  3. Zugriff im Code: process.env.CAPTCHAAI_API_KEY
// Alternative: use env var instead of input
const apiKey = input.captchaaiApiKey || process.env.CAPTCHAAI_API_KEY;

Apify-Proxy + CaptchaAI

const crawler = new PlaywrightCrawler({
    proxyConfiguration: await Actor.createProxyConfiguration({
        groups: ['RESIDENTIAL'],
    }),
    // ... rest of config
});

FAQ

Kann ich CaptchaAI im kostenlosen Kontingent von Apify verwenden?

Ja. CaptchaAI ist ein externer API-Aufruf, der auf jedem Apify-Plan funktioniert. Ihre Kosten sind der Thread-basierte Plan-Preis von CaptchaAI (unbegrenzte Lösungen pro Thread) zuzüglich der Rechenkosten von Apify.

Sollte ich Apify-Proxys oder den Proxy-Parameter von CaptchaAI verwenden?

Verwenden Sie Apify-Proxys zum Scraping von Anfragen und CaptchaAI ohne Proxys zum Lösen. Dies ist für die meisten Anwendungsfälle der kostengünstigste Ansatz.

Wie gehe ich mit Apify-Actor-Timeouts bei der CAPTCHA-Lösung um?

Stellen Sie requestHandlerTimeoutSecs auf mindestens 180 Sekunden ein, um CAPTCHA-Lösungszeit zu ermöglichen.


Verwandte Leitfäden

  • Crawlee + CaptchaAI-Integration
  • Scrapy + CaptchaAI-Integration

Stellen Sie CAPTCHA-lösende Actors bereit – Holen Sie sich CaptchaAI.

Kommentare sind für diesen Artikel deaktiviert.