Strona główna Dokumentacja Tutoriale Logowanie
Obsługiwane typy zadań
Metody API
Artykuły
Tutoriale
GitHub
Menu dokumentacja

Jak zastosować wtyczkę Anti-Captcha z Puppeteer oraz Selenium

Puppeteer i Selenium to dwa główne silniki służące automatyzacji przeglądarki, a nasz plugin idealnie z nimi współpracuje. W tym artykule pokażemy jak użyć go z Puppeteer i Selenium programując w językach NodeJS i Python. Jeśli zastanawiasz się nad wyborem pomiędzy nimi, zdecydowanie polecamy NodeJS+Puppeteer z racji natywnego środowiska.

1. Zainstaluj zależności. W przypadku NodeJS wystarczą poniższe paczki npm, zaś dla Python należy zainstalować paczki oraz binarkę "chromedriver" z tej strony. Wersja sterownika musi się zgadzać z wersją Chrome zainstalowaną w systemie.

NodeJS
          npm install adm-zip puppeteer puppeteer-extra puppeteer-extra-plugin-stealth
        
Python
          pip install selenium
        

2. Pobierz wtyczkę w formie ZIP dla Chrome, rozpakuj do folderu swego projektu. Rzeczywiste wersje znajdują się tu. Można to również zrobić drogą programowania:

NodeJS
          //npm install adm-zip
const https = require('https')
const fs = require('fs');
const AdmZip = require("adm-zip");

const pluginURL = 'https://antcpt.com/anticaptcha-plugin.zip';

(async () => {
    // pobierz plugin
    await new Promise((resolve) => {
        https.get(pluginURL, resp => resp.pipe(fs.createWriteStream('./plugin.zip').on('close', resolve)));
    })
    // rozpakuj
    const zip = new AdmZip("./plugin.zip");
    await zip.extractAllTo("./plugin/", true);
})();
        
Python
          import urllib.request
import zipfile

url = 'https://antcpt.com/anticaptcha-plugin.zip'
# pobierz plugin
filehandle, _ = urllib.request.urlretrieve(url)
# rozpakuj
with zipfile.ZipFile(filehandle, "r") as f:
    f.extractall("plugin")
        

3. Następnie skonfiguruj swój klucz API w pliku ./plugin/js/config_ac_api_key.js . Swój klucz API znajdziesz w strefie klienta. Aby wszystko zadziałało, twoje saldo musi być dodatnie.

NodeJS
          const apiKey = 'API_KEY_32_BYTES';
if (fs.existsSync('./plugin/js/config_ac_api_key.js')) {
    let confData = fs.readFileSync('./plugin/js/config_ac_api_key.js', 'utf8');
    confData = confData.replace(/antiCapthaPredefinedApiKey = ''/g, `antiCapthaPredefinedApiKey = '${apiKey}'`);
    fs.writeFileSync('./plugin/js/config_ac_api_key.js', confData, 'utf8');
} else {
    console.error('plugin configuration not found!')
}
        
Python
          from pathlib import Path
import zipfile

# ustaw klucz API w pliku konfiguracyjnym
api_key = "API_KEY_32_BYTES"
file = Path('./plugin/js/config_ac_api_key.js')
file.write_text(file.read_text().replace("antiCapthaPredefinedApiKey = ''", "antiCapthaPredefinedApiKey = '{}'".format(api_key)))

# spakuj katalog z pluginem z powrotem do plugin.zip
zip_file = zipfile.ZipFile('./plugin.zip', 'w', zipfile.ZIP_DEFLATED)
for root, dirs, files in os.walk("./plugin"):
        for file in files:
            path = os.path.join(root, file)
            zip_file.write(path, arcname=path.replace("./plugin/", ""))
zip_file.close()
        

4. Zainicjalizuj przeglądarkę z wtyczką. Dla Puppeteer zalecamy plugin 'puppeteer-extra-plugin-stealth' dla paczki 'puppeteer-extra', ukrywa on bowiem wszystkie przejawy zautomatyzowania przeglądarki Chromium.

NodeJS
          //npm install puppeteer puppeteer-extra puppeteer-extra-plugin-stealth
const puppeteer = require('puppeteer-extra');
const StealthPlugin = require('puppeteer-extra-plugin-stealth');
puppeteer.use(StealthPlugin());

(async () => {
    const browser = await puppeteer.launch({
        headless: false,
        ignoreDefaultArgs: [
            "--disable-extensions",
            "--enable-automation"
        ],
        args: [
            '--disable-web-security',
            '--disable-features=IsolateOrigins,site-per-process',
            '--allow-running-insecure-content',
            '--disable-blink-features=AutomationControlled',
            '--no-sandbox',
            '--mute-audio',
            '--no-zygote',
            '--no-xshm',
            '--window-size=1920,1080',
            '--no-first-run',
            '--no-default-browser-check',
            '--disable-dev-shm-usage',
            '--disable-gpu',
            '--enable-webgl',
            '--ignore-certificate-errors',
            '--lang=en-US,en;q=0.9',
            '--password-store=basic',
            '--disable-gpu-sandbox',
            '--disable-software-rasterizer',
            '--disable-background-timer-throttling',
            '--disable-backgrounding-occluded-windows',
            '--disable-renderer-backgrounding',
            '--disable-infobars',
            '--disable-breakpad',
            '--disable-canvas-aa',
            '--disable-2d-canvas-clip-aa',
            '--disable-gl-drawing-for-tests',
            '--enable-low-end-device-mode',
            '--disable-extensions-except=./plugin',
            '--load-extension=./plugin'
        ]
    });
    const page = await browser.newPage();
})();
        
Python
          from selenium import webdriver

options = webdriver.ChromeOptions()
options.add_extension('./plugin.zip')

browser = webdriver.Chrome('./chromedriver', options=options)
        

5. Przejdź na docelową stronę i wypełnij formularz, jeśli to konieczne. Wtyczka sama znajdzie Recaptcha i zacznie go rozwiązywać.

NodeJS
          (async () => {
    const url = 'https://anti-captcha.com/demo/?page=recaptcha_v2_textarea';
    const login = 'Test login';
    const password = 'Test password';

    try {
        await page.goto(url, {
            waitUntil: "networkidle0"
        });
    } catch (e) {
        console.error('err while loading the page: '+e);
    }
    // wyłącz nawigacyjne błędy przekroczenia limitu czasu oczekiwania
    await page.setDefaultNavigationTimeout(0);

    await page.$eval('#login', (element, login) => {
        element.value = login;
    }, login);
    await page.$eval('#password', (element, password) => {
        element.value = password;
    }, password);

})();
        
Python
          browser.get('https://anti-captcha.com/demo/?page=recaptcha_v2_textarea')

# filling form
browser.find_element_by_css_selector('#login').send_keys('Test login')
browser.find_element_by_css_selector('#password').send_keys('Test password')

        

6. Tu na chwilkę się zatrzymajmy. Niektóre formularze w sieci wymagają wciśnięcia guzika prześlij (submit) po rozwiązaniu Recaptcha, a inne stosują funkcję callback i przesyłają je automatycznie. W pierwszym przypadku chcemy wcisnąć przycisk submit tuż po rozwiązaniu Recaptchy. Aby zrobić to w odpowiednim momencie, musimy po prostu poczekać na pojawienie się selektora .antigate_solver.solved i wówczas wcisnąć przycisk przesyłania.

NodeJS
          // poczekaj, aż pojawi się selektor "solved"
await page.waitForSelector('.antigate_solver.solved').catch(error => console.log('failed to wait for the selector'));
console.log('recaptcha rozwiązana');

// wciśnij przycisk "wyślij" (submit)
await Promise.all([
    page.click('#submitButton'),
    page.waitForNavigation({ waitUntil: "networkidle0" })
]);
console.log('zadanie wykonane, formularz z recaptcha ominięty');
        
Python
          # poczekaj, aż pojawi się selektor "solved"
webdriver.support.wait.WebDriverWait(browser, 120).until(lambda x: x.find_element_by_css_selector('.antigate_solver.solved'))
# wciśnij przycisk "wyślij" (submit)
browser.find_element_by_css_selector('#submitButton').click()
        

To tyle, formularz wypełniony, Recaptcha rozwiązana i ominięta. Przykłady kodu:

NodeJS
          // first run the following to install required npm packages:
//
// npm install adm-zip follow-redirects puppeteer puppeteer-extra puppeteer-extra-plugin-stealth
//
//
const https = require('follow-redirects').https;
const fs = require('fs');
const AdmZip = require("adm-zip");

const apiKey = 'YOUR_API_KEY_HERE!';
const pluginURL = 'https://antcpt.com/anticaptcha-plugin.zip';
const url = 'https://anti-captcha.com/demo/?page=recaptcha_v2_textarea';
const login = 'Test login';
const password = 'Test password';
let page = null;


const puppeteer = require('puppeteer-extra');
const StealthPlugin = require('puppeteer-extra-plugin-stealth');
puppeteer.use(StealthPlugin());

(async () => {
    // pobierz plugin
    await new Promise((resolve) => {
        https.get(pluginURL, resp => resp.pipe(fs.createWriteStream('./plugin.zip').on('close', resolve)));
    })
    // rozpakuj
    const zip = new AdmZip("./plugin.zip");
    await zip.extractAllTo("./plugin/", true);

    // ustaw klucz API w pliku konfiguracyjnym
    await new Promise((resolve, reject) => {
        if (fs.existsSync('./plugin/js/config_ac_api_key.js')) {
            let confData = fs.readFileSync('./plugin/js/config_ac_api_key.js', 'utf8');
            confData = confData.replace(/antiCapthaPredefinedApiKey = ''/g, `antiCapthaPredefinedApiKey = '${apiKey}'`);
            fs.writeFileSync('./plugin/js/config_ac_api_key.js', confData, 'utf8');
            resolve();
        } else {
            console.error('plugin configuration not found!')
            reject();
        }
    });

    // ustaw opcje uruchamianej przeglądarki
    const options = {
        headless: false,
        ignoreDefaultArgs: [
            "--disable-extensions",
            "--enable-automation"
        ],
        args: [
            '--disable-web-security',
            '--disable-features=IsolateOrigins,site-per-process',
            '--allow-running-insecure-content',
            '--disable-blink-features=AutomationControlled',
            '--no-sandbox',
            '--mute-audio',
            '--no-zygote',
            '--no-xshm',
            '--window-size=1920,1080',
            '--no-first-run',
            '--no-default-browser-check',
            '--disable-dev-shm-usage',
            '--disable-gpu',
            '--enable-webgl',
            '--ignore-certificate-errors',
            '--lang=en-US,en;q=0.9',
            '--password-store=basic',
            '--disable-gpu-sandbox',
            '--disable-software-rasterizer',
            '--disable-background-timer-throttling',
            '--disable-backgrounding-occluded-windows',
            '--disable-renderer-backgrounding',
            '--disable-infobars',
            '--disable-breakpad',
            '--disable-canvas-aa',
            '--disable-2d-canvas-clip-aa',
            '--disable-gl-drawing-for-tests',
            '--enable-low-end-device-mode',
            '--disable-extensions-except=./plugin',
            '--load-extension=./plugin'
        ]
    }

    try {
        // uruchom przeglądarkę z wtyczką
        const browser = await puppeteer.launch();
        page = await browser.newPage();
    } catch (e) {
        console.log('could not launch browser: '+e.toString())
        return;
    }

    // przejdź na docelową stronę
    try {
        await page.goto(url, {
            waitUntil: "networkidle0"
        });
    } catch (e) {
        console.error('err while loading the page: '+e);
    }

    // wyłącz nawigacyjne błędy przekroczenia limitu czasu oczekiwania
    await page.setDefaultNavigationTimeout(0);

    // wypełnij formularz
    await page.$eval('#login', (element, login) => {
        element.value = login;
    }, login);
    await page.$eval('#password', (element, password) => {
        element.value = password;
    }, password);

    // poczekaj, aż pojawi się selektor "solved"
    await page.waitForSelector('.antigate_solver.solved').catch(error => console.log('failed to wait for the selector'));
    console.log('recaptcha rozwiązana');

    // wciśnij przycisk "wyślij" (submit)
    await Promise.all([
        page.click('#submitButton'),
        page.waitForNavigation({ waitUntil: "networkidle0" })
    ]);
    console.log('recaptcha rozwiązana');

})();
        
Python
          import urllib.request
import zipfile
import os
from pathlib import Path
from selenium import webdriver

# pobierz plugin
url = 'https://antcpt.com/anticaptcha-plugin.zip'
filehandle, _ = urllib.request.urlretrieve(url)
# rozpakuj
with zipfile.ZipFile(filehandle, "r") as f:
    f.extractall("plugin")

# ustaw klucz API w pliku konfiguracyjnym
api_key = "YOUR_API_KEY_HERE!"
file = Path('./plugin/js/config_ac_api_key.js')
file.write_text(file.read_text().replace("antiCapthaPredefinedApiKey = ''", "antiCapthaPredefinedApiKey = '{}'".format(api_key)))

# spakuj katalog z pluginem z powrotem do plugin.zip
zip_file = zipfile.ZipFile('./plugin.zip', 'w', zipfile.ZIP_DEFLATED)
for root, dirs, files in os.walk("./plugin"):
        for file in files:
            path = os.path.join(root, file)
            zip_file.write(path, arcname=path.replace("./plugin/", ""))
zip_file.close()

# ustaw opcje uruchamianej przeglądarki
options = webdriver.ChromeOptions()
options.add_extension('./plugin.zip')

# ustaw opcje uruchamianej przeglądarki
browser = webdriver.Chrome('./chromedriver', options=options)

# przejdź na docelową stronę
browser.get('https://anti-captcha.com/demo/?page=recaptcha_v2_textarea')

# wypełnij formularz
browser.find_element_by_css_selector('#login').send_keys('Test login')
browser.find_element_by_css_selector('#password').send_keys('Test password')

# poczekaj, aż pojawi się selektor "solved"
webdriver.support.wait.WebDriverWait(browser, 120).until(lambda x: x.find_element_by_css_selector('.antigate_solver.solved'))

# wciśnij przycisk "wyślij" (submit)
browser.find_element_by_css_selector('#submitButton').click()
        

Bonus: potrzebna jest pewna sztuczka, by móc uruchamiać wtyczki w trybie headless (bez ekranu), gdyż Chrome nie obsługuje automatyzacji przeglądarki za pomocą wtyczek. Stosujemy wówczas narzędzie zwane Xvfb, które wyposaży twoją aplikację w wirtualny pulpit.

bash
          # zainstaluj pakiet
apt-get install -y xvfb

# ustaw zmienną display
export DISPLAY=:0

# uruchom demona Xvfb w tle (tylko raz)
/usr/bin/Xvfb :0 -screen 0 1024x768x24 &

# poczekaj trochę, aby zdążył się uruchomić (tylko raz)
sleep 5

# dodaj prefix "xvfb-run" do skryptu "node" lub "python"
xvfb-run node myscript.js
# lub
xvfb-run python myscript.py