Menu

Anti-CaptchaプラグインをPuppeteerまたはSeleniumに適用する方法

ブラウザ自動化の時、PuppeteerとSeleniumは2つの主要なエンジンであり、当社のプラグインはそれらにシームレスに統合できます。ここで、NodeJSとPythonプログラミング言語を使ってPuppeteerとSeleniumに適用する方法をそれぞれ説明します。この2つから選択する場合は、ネイティブ環境としてNodeJS + Puppeteerの組み合わせを強くお勧めします。

1.依存関係をインストールします。NodeJSの場合は、以下の所定のnpmパッケージをインストールするだけです。Pythonの場合は、パッケージをインストールして、このページから実行ファイル「chromedriver」 をダウンロードしてください。ドライバのバージョンは、システムにインストールされているChromeのバージョンと一致している必要があります。

Node.js
Python
npm install adm-zip puppeteer puppeteer-extra puppeteer-extra-plugin-stealth
pip3 install selenium

2.Chrome用のZIP版プラグインをダウンロードし、プロジェクトフォルダに解凍してください。実際のバージョンはここにあります。プログラムでも可能です。

Node.js
Python
//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 () => {
    // プラグインをダウンロードします
    await new Promise((resolve) => {
        https.get(pluginURL, resp => resp.pipe(fs.createWriteStream('./plugin.zip').on('close', resolve)));
    })
    // 解凍します
    const zip = new AdmZip("./plugin.zip");
    await zip.extractAllTo("./plugin/", true);
})();
import urllib.request
import zipfile

url = 'https://antcpt.com/anticaptcha-plugin.zip'
# プラグインをダウンロードします
filehandle, _ = urllib.request.urlretrieve(url)
# 解凍します
with zipfile.ZipFile(filehandle, "r") as f:
    f.extractall("plugin")

3.次に、./plugin/js/config_ac_api_key.jsファイルにAPIキーを設定します。APIキーはカスタマーエリアにあります。動作させるためには、いくらかのプラス残高が必要です。

Node.js
Python
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!')
}
from pathlib import Path
import zipfile

# `+t('articles.how-to-integrate.code-comments.set-api-key')+`
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)))

# `+t('articles.how-to-integrate.code-comments.zip-back')+`
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.プラグインでブラウザの設定を初期化します。Puppeteerの場合、「puppeteer-extra」パッケージ用のプラグイン「puppeteer-extra-plugin-stealth」をお勧めします。これにより、ウェブ自動化Chromiumブラウザのすべての形跡が隠されます。

Node.js
Python
//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();
})();
from selenium import webdriver

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

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

5.ターゲットページに移動し、必要に応じてフォームに記入します。プラグインが自動的にRecaptchaをピックアップして解決を開始します。

Node.js
Python
(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);
    }
    // `+t('articles.how-to-integrate.code-comments.disable-timeouts')+`
    await page.setDefaultNavigationTimeout(0);

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

})();
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. 次は少しトリッキーな部分です。一部ののウェブフォームでは、Recaptchaを解いた後に送信ボタンを押す必要がありますが、ではコールバックを利用して自動的に送信します。最初のケースでは、Recaptcha を解いた直後に送信ボタンを押したいです。これを適切なタイミングで行うには、単にセレクタ .antigate_solver.solved が表示されるのを待ち、送信ボタンを押せばよいです。

Node.js
Python
// 「solved」セレクターが表示されるのを待ちます
await page.waitForSelector('.antigate_solver.solved').catch(error => console.log('failed to wait for the selector'));
console.log('recaptcha解決');

// 送信ボタンを押します
await Promise.all([
    page.click('#submitButton'),
    page.waitForNavigation({ waitUntil: "networkidle0" })
]);
console.log('タスクが完了し、recaptchaがバイパスされました ');
# 「solved」セレクターが表示されるのを待ちます
webdriver.support.wait.WebDriverWait(browser, 120).until(lambda x: x.find_element_by_css_selector('.antigate_solver.solved'))
# articles.how-to-integrate.code-comments.press-submit
browser.find_element_by_css_selector('#submitButton').click()

これで、フォーム記入が完成し、Recaptchaが解決されバイパスされました。完全なコード例は以下です:

Node.js
Python

Node.js で Anti-Captcha ブラウザ拡張機能を統合する方法

// 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 () => {
    // プラグインをダウンロードします
    await new Promise((resolve) => {
        https.get(pluginURL, resp => resp.pipe(fs.createWriteStream('./plugin.zip').on('close', resolve)));
    })
    // 解凍します
    const zip = new AdmZip("./plugin.zip");
    await zip.extractAllTo("./plugin/", true);

    // 設定ファイルでAPIキーを設定します
    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();
        }
    });

    // ブラウザの起動オプションを設定します
    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 {
        // プラグインでブラウザを起動します
        const browser = await puppeteer.launch();
        page = await browser.newPage();
    } catch (e) {
        console.log('could not launch browser: '+e.toString())
        return;
    }

    // ターゲットページに移動します
    try {
        await page.goto(url, {
            waitUntil: "networkidle0"
        });
    } catch (e) {
        console.error('err while loading the page: '+e);
    }

    // ナビゲーションタイムアウトエラーを無効にします
    await page.setDefaultNavigationTimeout(0);

    // フォームに記入します
    await page.$eval('#login', (element, login) => {
        element.value = login;
    }, login);
    await page.$eval('#password', (element, password) => {
        element.value = password;
    }, password);

    // 「solved」セレクターが表示されるのを待ちます
    await page.waitForSelector('.antigate_solver.solved').catch(error => console.log('failed to wait for the selector'));
    console.log('recaptcha解決');

    // 送信ボタンを押します
    await Promise.all([
        page.click('#submitButton'),
        page.waitForNavigation({ waitUntil: "networkidle0" })
    ]);
    console.log('recaptcha解決');

})();

Python で Anti-Captcha ブラウザ拡張機能を統合する方法

import urllib.request
import zipfile
import os
from pathlib import Path
from selenium import webdriver

# プラグインをダウンロードします
url = 'https://antcpt.com/anticaptcha-plugin.zip'
filehandle, _ = urllib.request.urlretrieve(url)
# 解凍します
with zipfile.ZipFile(filehandle, "r") as f:
    f.extractall("plugin")

# 設定ファイルでAPIキーを設定します
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)))

# プラグインディレクトリを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()

# ブラウザの起動オプションを設定します
options = webdriver.ChromeOptions()
options.add_extension('./plugin.zip')

# ブラウザの起動オプションを設定します
browser = webdriver.Chrome('./chromedriver', options=options)

# ターゲットページに移動します
browser.get('https://anti-captcha.com/demo/?page=recaptcha_v2_textarea')

# フォームに記入します
browser.find_element_by_css_selector('#login').send_keys('Test login')
browser.find_element_by_css_selector('#password').send_keys('Test password')

# 「solved」セレクターが表示されるのを待ちます
webdriver.support.wait.WebDriverWait(browser, 120).until(lambda x: x.find_element_by_css_selector('.antigate_solver.solved'))

# 送信ボタンを押します
browser.find_element_by_css_selector('#submitButton').click()

おまけ:Chromeはプラグインによるブラウザの自動化をサポートしていないので、ヘッドレスモードでプラグインを実行するトリックがあります。アプリケーションに仮想デスクトップを提供するXvfbというユーティリティを使ってください。

Node.js
Python
# パッケージをインストールします
apt-get install -y xvfb

# 表示変数を設定します
export DISPLAY=:0

# Xvfbをデーモンとしてバックグラウンドで起動します(1回のみ)
/usr/bin/Xvfb :0 -screen 0 1024x768x24 &

# 表示するまでしばらく待ちます(1回のみ)
sleep 5

# プレフィックス「xvfb-run」を「node」または「python」スクリプトに追加します
xvfb-run node myscript.js
# パッケージをインストールします
apt-get install -y xvfb

# 表示変数を設定します
export DISPLAY=:0

# Xvfbをデーモンとしてバックグラウンドで起動します(1回のみ)
/usr/bin/Xvfb :0 -screen 0 1024x768x24 &

# 表示するまでしばらく待ちます(1回のみ)
sleep 5

# プレフィックス「xvfb-run」を「node」または「python」スクリプトに追加します
xvfb-run python myscript.py