Menu

Puppeteer या Selenium में Anti-Captcha प्लग-इन का इस्तेमाल कैसे करें

Puppeteer और Selenium ब्राउज़र ऑटोमेशन के दो प्रमुख इंजन हैं व हमारा प्लग-इन बड़ी आसानी से उनमें इंटीग्रेट हो जाता है। इस आर्टिकल में हम आपको दिखाएँगे कि NodeJS और Python प्रोग्रामिंग लैंग्वेजों के लिए क्रमशः Puppeteer और Selenium में उसका इस्तेमाल कैसे किया जाता है। अगर आप इन दोनों में से किसी एक का चयन करने वाले हैं, तो अपने मूल एनवायरनमेंट के चलते हम आपको 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
// "हल किए गए" सिलेक्टर के दिखाई देने का इंतज़ार करें
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 फ़ॉर्म बायपास हुआ ');
# "हल किए गए" सिलेक्टर के दिखाई देने का इंतज़ार करें
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);

    // "हल किए गए" सिलेक्टर के दिखाई देने का इंतज़ार करें
    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')

# "हल किए गए" सिलेक्टर के दिखाई देने का इंतज़ार करें
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 daemon शुरू कर दें (सिर्फ़ एक बार)
/usr/bin/Xvfb :0 -screen 0 1024x768x24 &

# उसके दिखाई देने तक थोड़ा इंतज़ार करें (सिर्फ़ एक बार)
sleep 5

# "node" या "python" स्क्रिप्ट में "xvfb-run" प्रीफिक्स जोड़ दें
xvfb-run node myscript.js
# पैकेज को इनस्टॉल कर लें
apt-get install -y xvfb

# डिस्प्ले वेरिएबल को निर्दिष्ट कर दें
export DISPLAY=:0

# बैकग्राउंड में Xvfb daemon शुरू कर दें (सिर्फ़ एक बार)
/usr/bin/Xvfb :0 -screen 0 1024x768x24 &

# उसके दिखाई देने तक थोड़ा इंतज़ार करें (सिर्फ़ एक बार)
sleep 5

# "node" या "python" स्क्रिप्ट में "xvfb-run" प्रीफिक्स जोड़ दें
xvfb-run python myscript.py