Selenium 連携
Selenium + CaptchaSonic
Selenium WebDriverの自動化プロジェクト向けに、Pythonを中心にCAPTCHAを解決します。
npm
クイックインストール
pip install captchasonic selenium01
インポートして設定
Selenium WebDriverと CaptchaSonic Python SDKを設定します。
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from captchasonic import CaptchaSonic
# Solves over a native gRPC connection (no HTTP overhead)
client = CaptchaSonic("sonic_your_key_here")02
対象に移動
ブラウザを起動し、CAPTCHAのあるページに移動します。
driver = webdriver.Chrome()
driver.get("https://example.com/login")
# Wait for captcha to load
WebDriverWait(driver, 10).until(
EC.presence_of_element_located(
(By.CSS_SELECTOR, "iframe[src*='recaptcha']")
)
)03
sitekeyを取得して解決
CAPTCHAのパラメータを取得し、CaptchaSonicに送信します。
# Get the sitekey from the page
sitekey = driver.find_element(
By.CSS_SELECTOR, "[data-sitekey]"
).get_attribute("data-sitekey")
# Solve with CaptchaSonic over gRPC
result = client.solve_recaptcha_v2_token(
website_url=driver.current_url,
website_key=sitekey,
)
token = result["solution"]["gRecaptchaResponse"]
print(f"Token: {token}")04
挿入して送信
解決トークンを適用し、フォームを送信します。
# Inject the token
driver.execute_script(f"""
document.getElementById('g-recaptcha-response')
.innerHTML = '{token}';
""")
# Submit the form
driver.find_element(By.CSS_SELECTOR, "button[type='submit']").click()
# Wait for page transition
WebDriverWait(driver, 10).until(
EC.url_changes(driver.current_url))
print("Captcha bypassed successfully!")Links