티스토리 뷰

반응형

🚀 Selenium과 AI OCR을 활용한 CAPTCHA 자동 입력 방법

웹사이트에서 **CAPTCHA(자동입력방지 문자)**는 봇을 막기 위해 사용됩니다. 하지만 **Selenium과 AI OCR(광학 문자 인식, Optical Character Recognition)**을 활용하면 자동으로 CAPTCHA를 분석하고 입력하는 자동화를 구현할 수 있습니다.


1. CAPTCHA 자동 입력의 핵심 개념

CAPTCHA는 일반적으로 이미지 또는 문자 입력 방식으로 제공됩니다.

CAPTCHA 유형 설명 해결 방법

숫자 또는 문자 입력 사용자가 보이는 문자를 입력 OCR(광학 문자 인식) 활용
Google reCAPTCHA 클릭 또는 이미지 선택 AI Solver 서비스 이용 (ex. 2Captcha)
Invisible CAPTCHA 봇 탐지 기반 자동 차단 Selenium 우회 기법 적용

📌 오늘 다룰 내용
Selenium을 이용한 CAPTCHA 이미지 크롤링
Tesseract-OCR을 이용한 문자 인식 자동화
2Captcha API를 활용한 Google reCAPTCHA 자동화


2. 프로젝트 1: CAPTCHA 문자 자동 입력 (Tesseract-OCR 활용)

Tesseract-OCR은 **이미지에서 문자 인식(OCR)**을 수행하는 오픈소스 라이브러리입니다.

🔹 (1) 필요 패키지 설치

pip install selenium pillow pytesseract

🔹 추가 설치 (Tesseract-OCR 엔진 다운로드)


🔹 (2) CAPTCHA 자동 입력 코드

import time
import pytesseract
from PIL import Image
from selenium import webdriver
from selenium.webdriver.common.by import By

# 1️⃣ Chrome WebDriver 실행
driver = webdriver.Chrome()
driver.get("https://example.com/captcha")  # CAPTCHA가 있는 사이트

time.sleep(2)  # 페이지 로딩 대기

# 2️⃣ CAPTCHA 이미지 다운로드
captcha_element = driver.find_element(By.ID, "captcha-img")
captcha_element.screenshot("captcha.png")  # 캡차 이미지 저장

# 3️⃣ OCR을 이용한 문자 인식
pytesseract.pytesseract.tesseract_cmd = r"C:\Program Files\Tesseract-OCR\tesseract.exe"  # Tesseract 경로
captcha_text = pytesseract.image_to_string(Image.open("captcha.png"))

print("인식된 CAPTCHA:", captcha_text.strip())

# 4️⃣ CAPTCHA 입력 및 제출
captcha_input = driver.find_element(By.ID, "captcha-input")
captcha_input.send_keys(captcha_text.strip())

submit_button = driver.find_element(By.ID, "submit-btn")
submit_button.click()

time.sleep(3)
driver.quit()

🔹 설명

  • captcha_element.screenshot("captcha.png") : Selenium을 이용해 CAPTCHA 이미지를 저장
  • pytesseract.image_to_string() : OCR을 이용해 CAPTCHA 문자 자동 인식
  • send_keys() : 인식된 텍스트를 입력 후 자동 제출

🟢 Tip:

  • CAPTCHA의 배경이 복잡하면 인식률이 낮아질 수 있음.
  • Pillow를 활용해 이미지를 전처리(흑백 변환, 노이즈 제거) 하면 인식률이 향상됨.

3. 프로젝트 2: Google reCAPTCHA 자동 우회 (2Captcha API 활용)

Google reCAPTCHA는 일반적인 OCR 방식으로 해결할 수 없기 때문에 2Captcha 같은 AI 솔버를 이용해야 합니다.

🔹 (1) 2Captcha 계정 생성 및 API Key 발급

  1. 2Captcha 홈페이지에서 회원가입
  2. API Key 발급

🔹 (2) reCAPTCHA 자동 해결 코드

import requests
from selenium import webdriver
from selenium.webdriver.common.by import By
import time

# 1️⃣ Selenium으로 사이트 이동
driver = webdriver.Chrome()
driver.get("https://www.google.com/recaptcha/api2/demo")

time.sleep(3)  # 페이지 로딩 대기

# 2️⃣ CAPTCHA 키 가져오기
site_key = driver.find_element(By.CLASS_NAME, "g-recaptcha").get_attribute("data-sitekey")
api_key = "YOUR_2CAPTCHA_API_KEY"

# 3️⃣ 2Captcha API 요청
url = f"http://2captcha.com/in.php?key={api_key}&method=userrecaptcha&googlekey={site_key}&pageurl=https://www.google.com/recaptcha/api2/demo"
response = requests.get(url)
captcha_id = response.text.split("|")[-1]

# 4️⃣ 해결된 CAPTCHA 응답 받기
time.sleep(15)  # AI 해결 대기
solution_url = f"http://2captcha.com/res.php?key={api_key}&action=get&id={captcha_id}"
solution = requests.get(solution_url).text.split("|")[-1]

# 5️⃣ CAPTCHA 입력 및 제출
driver.execute_script(f'document.getElementById("g-recaptcha-response").innerHTML="{solution}";')
time.sleep(2)
driver.find_element(By.ID, "recaptcha-demo-submit").click()

print("CAPTCHA 자동 해결 완료!")
time.sleep(3)
driver.quit()

🔹 설명

  • site_key = driver.find_element(By.CLASS_NAME, "g-recaptcha").get_attribute("data-sitekey")
    • Google reCAPTCHA의 **사이트 키(site-key)**를 가져옴
  • 2Captcha API를 이용해 CAPTCHA 자동 해결 요청 (requests.get(url))
  • document.getElementById("g-recaptcha-response").innerHTML="해결된 키";
    • 해결된 키를 HTML에 직접 삽입 후 제출

🟢 Tip:

  • 2Captcha API를 사용할 때 요청 후 10~15초 대기해야 AI가 해결할 수 있음.
  • 여러 개의 CAPTCHA를 해결해야 할 경우, 멀티쓰레딩을 사용하면 효율적.

4. CAPTCHA 우회 자동화 전략

CAPTCHA 유형 해결 방법

일반 이미지 문자 Tesseract-OCR로 이미지 문자 인식
Google reCAPTCHA v2 2Captcha, Anti-Captcha 같은 AI Solver 활용
Google reCAPTCHA v3 웹사이트 행동 패턴 분석 후 해결
Invisible CAPTCHA Selenium에서 execute_script()로 직접 응답값 삽입

5. 정리 및 결론

Selenium과 OCR을 조합하면 CAPTCHA 자동 입력이 가능
Google reCAPTCHA는 AI Solver(2Captcha)를 활용해야 함
CAPTCHA 보안이 강한 경우, Selenium 단독으로는 해결이 어려움

🔹 추천 추가 학습

  • AI 기반 CAPTCHA 분석 모델 개발 (OpenCV + Deep Learning)
  • Python으로 AutoBot 제작 후 API 연결

#selenium #selenium리캡챠자동입력 #OCR #셀레니윰 #셀레니윰리캡챠우회 #리캡챠우회

반응형