Playwright cung cấp tính năng tự động hóa trình duyệt đáng tin cậy trên Chrome, Firefox và WebKit. Khi các trang đích phân phát CAPTCHA, CaptchaAI sẽ giải quyết chúng ở phía máy chủ trong khi Playwright xử lý tương tác với trình duyệt.
Yêu cầu
| Yêu cầu | Chi tiết |
|---|---|
| Python | pip install playwright requests rồi playwright install |
| Node.js | npm install playwright axios |
| Khóa API CaptchaAI | Từcaptchaai.com |
Python: Nhà viết kịch + CaptchaAI
thiết lập
from playwright.sync_api import sync_playwright
import requests
import time
API_KEY = "YOUR_API_KEY"
def solve_recaptcha(site_key, page_url):
resp = requests.get("https://ocr.captchaai.com/in.php", params={
"key": API_KEY,
"method": "userrecaptcha",
"googlekey": site_key,
"pageurl": page_url
})
if not resp.text.startswith("OK|"):
raise Exception(resp.text)
task_id = resp.text.split("|")[1]
for _ in range(60):
time.sleep(5)
result = requests.get("https://ocr.captchaai.com/res.php", params={
"key": API_KEY, "action": "get", "id": task_id
})
if result.text == "CAPCHA_NOT_READY": continue
if result.text.startswith("OK|"): return result.text.split("|")[1]
raise Exception(result.text)
raise TimeoutError()
Ví dụ đầy đủ
def login_with_captcha(url, username, password):
with sync_playwright() as p:
browser = p.chromium.launch(headless=True)
context = browser.new_context(
user_agent="Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36"
)
page = context.new_page()
page.goto(url)
# Fill login form
page.fill("#username", username)
page.fill("#password", password)
# Check for reCAPTCHA
recaptcha = page.query_selector(".g-recaptcha")
if recaptcha:
site_key = recaptcha.get_attribute("data-sitekey")
print(f"Solving reCAPTCHA: {site_key}")
token = solve_recaptcha(site_key, page.url)
# Inject token
page.evaluate(f"""
document.getElementById('g-recaptcha-response').innerHTML = '{token}';
document.getElementById('g-recaptcha-response').style.display = '';
""")
# Submit
page.click('button[type="submit"]')
page.wait_for_load_state("networkidle")
print(f"Current URL: {page.url}")
content = page.content()
browser.close()
return content
result = login_with_captcha(
"https://staging.example.com/qa-login",
"user@example.com",
"password123"
)
Phiên bản không đồng bộ
from playwright.async_api import async_playwright
import aiohttp
import asyncio
async def solve_recaptcha_async(site_key, page_url):
async with aiohttp.ClientSession() as session:
params = {
"key": API_KEY, "method": "userrecaptcha",
"googlekey": site_key, "pageurl": page_url
}
async with session.get("https://ocr.captchaai.com/in.php", params=params) as resp:
text = await resp.text()
task_id = text.split("|")[1]
for _ in range(60):
await asyncio.sleep(5)
params = {"key": API_KEY, "action": "get", "id": task_id}
async with session.get("https://ocr.captchaai.com/res.php", params=params) as resp:
text = await resp.text()
if text == "CAPCHA_NOT_READY": continue
if text.startswith("OK|"): return text.split("|")[1]
raise Exception(text)
raise TimeoutError()
async def main():
async with async_playwright() as p:
browser = await p.chromium.launch(headless=True)
page = await browser.new_page()
await page.goto("https://example.com/form")
site_key = await page.get_attribute(".g-recaptcha", "data-sitekey")
token = await solve_recaptcha_async(site_key, page.url)
await page.evaluate(f"document.getElementById('g-recaptcha-response').innerHTML = '{token}'")
await page.click('button[type="submit"]')
await browser.close()
asyncio.run(main())
Node.js: Nhà viết kịch + CaptchaAI
const { chromium } = require("playwright");
const axios = require("axios");
const API_KEY = "YOUR_API_KEY";
async function solveRecaptcha(siteKey, pageUrl) {
const submit = await axios.get("https://ocr.captchaai.com/in.php", {
params: {
key: API_KEY,
method: "userrecaptcha",
googlekey: siteKey,
pageurl: pageUrl,
},
});
const taskId = submit.data.split("|")[1];
while (true) {
await new Promise((r) => setTimeout(r, 5000));
const result = await axios.get("https://ocr.captchaai.com/res.php", {
params: { key: API_KEY, action: "get", id: taskId },
});
if (result.data === "CAPCHA_NOT_READY") continue;
if (result.data.startsWith("OK|")) return result.data.split("|")[1];
throw new Error(result.data);
}
}
(async () => {
const browser = await chromium.launch({ headless: true });
const page = await browser.newPage();
await page.goto("https://staging.example.com/qa-login");
// Fill form
await page.fill("#username", "user@example.com");
await page.fill("#password", "password123");
// Solve CAPTCHA
const siteKey = await page.getAttribute(".g-recaptcha", "data-sitekey");
if (siteKey) {
const token = await solveRecaptcha(siteKey, page.url());
await page.evaluate(
(t) => (document.getElementById("g-recaptcha-response").innerHTML = t),
token
);
}
// Submit
await page.click('button[type="submit"]');
await page.waitForLoadState("networkidle");
console.log("Logged in:", page.url());
await browser.close();
})();
Xử lý Cloudflare Turnstile
# Detect Turnstile
turnstile = page.query_selector(".cf-turnstile")
if turnstile:
site_key = turnstile.get_attribute("data-sitekey")
resp = requests.get("https://ocr.captchaai.com/in.php", params={
"key": API_KEY, "method": "turnstile",
"sitekey": site_key, "pageurl": page.url
})
task_id = resp.text.split("|")[1]
# Poll and inject...
Nhà viết kịch vs Selenium vs Puppeteer
| tính năng | Nhà viết kịch | Selen | Puppeteer |
|---|---|---|---|
| Ngôn ngữ | Python, Node.js, C#, Java | Python, Java, C#, Ruby, JS | Node.js |
| Trình duyệt | Crom, Firefox, WebKit | Chrome, Firefox, Edge, Safari | crom |
| Tự động chờ | ✅ Tích hợp sẵn | Œ Chờ thủ công | ⚠️ Một phần |
| Chặn mạng | ✅ | ⚠️ Có giới hạn | ✅ |
| Tích hợp CaptchaAI | ✅ Cùng một API | ✅ Cùng một API | ✅ Cùng một API |
CaptchaAI hoạt động giống hệt nhau với cả ba – trích xuất khóa trang web, giải quyết thông qua API, tiêm mã thông báo.
Khắc phục sự cố
| vấn đề | sửa chữa |
|---|---|
page.query_selector trả về giá trị rỗng |
CAPTCHA tải động; sử dụng page.wait_for_selector() |
| Việc tiêm mã thông báo không hoạt động | Kiểm tra xem vùng văn bản phản hồi có ID khác không |
| Nhà viết kịch gặp sự cố trong Docker | Cài đặt phụ thuộc trình duyệt: playwright install-deps |
| CAPTCHA xuất hiện lại sau khi giải quyết | Trang web có thể yêu cầu thực hiện gọi lại; kích hoạt nó thông qua page.evaluate() |
Câu hỏi thường gặp
Tính năng tự động chờ của Playwright có giúp ích cho CAPTCHA không?
Tính năng tự động chờ của Playwright đảm bảo các phần tử hiển thị trước khi tương tác nhưng sẽ không giải được CAPTCHA. Bạn cần CaptchaAI để giải quyết thực tế.
Tôi có thể sử dụng Playwright với tất cả các loại CAPTCHA không?
Vâng. CaptchaAI xử lý việc giải quyết thông qua API - Playwright chỉ cần trích xuất khóa trang web và đưa mã thông báo vào. Tính năng này hoạt động với reCAPTCHA, Turnstile, hCaptcha và tất cả các loại được hỗ trợ khác.
Playwright có tốt hơn Selenium trong việc tự động hóa CAPTCHA không?
Tính năng tự động chờ tích hợp sẵn của Playwright và thiết kế API tốt hơn giúp quy trình làm việc của CAPTCHA trở nên đáng tin cậy hơn. Việc tích hợp CaptchaAI giống hệt nhau cho cả hai.
Hướng dẫn liên quan
- Xử lý CAPTCHA Selenium bằng Python
- Puppeteer giải CAPTCHA bằng Node.js
- Xử lý CAPTCHA đăng nhập tự động