Playwright 跨 Chromium、Firefox 和 WebKit 提供可靠的浏览器自动化。当目标页面提供验证码时,CaptchaAI 在服务器端解决它们,而 Playwright 处理浏览器交互。
要求
| 要求 | 细节 |
|---|---|
| Python | pip install playwright requests 然后 playwright install |
| Node.js | npm install playwright axios |
| CaptchaAI API 密钥 | 从验证码网站 |
Python:剧作家 + CaptchaAI
设置
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()
完整示例
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"
)
异步版本
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:剧作家 + 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();
})();
处理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...
剧作家 vs Selenium vs Puppeteer
| 特征 | 剧作家 | 硒 | Puppeteer |
|---|---|---|---|
| 语言 | Python、Node.js、C#、Java | Python、Java、C#、Ruby、JS | Node.js |
| 浏览器 | 铬、火狐、WebKit | Chrome、火狐、Edge、Safari | 铬 |
| 自动等待 | Ø...内置 | Ø 手动等待 | ✍ 部分 |
| 网络拦截 | ○… | ✍有限公司 | ○… |
| CaptchaAI 集成 | âœ...相同的 API | âœ...相同的 API | âœ...相同的 API |
CaptchaAI 与这三者的工作方式相同 - 提取站点密钥、通过 API 解决、注入令牌。
故障排除
| 问题 | 处理方式 |
|---|---|
page.query_selector 返回 null |
验证码动态加载;使用page.wait_for_selector() |
| token 提交不起作用 | 检查响应文本区域是否具有不同的 ID |
| Playwright 在 Docker 中崩溃 | 安装浏览器依赖项:playwright install-deps |
| 验证码解决后重新出现 | 站点可能需要回调执行;通过 page.evaluate() 触发 |
常问问题
Playwright 的自动等待功能对验证码有帮助吗?
Playwright 的自动等待可确保元素在交互之前可见,但它无法解决验证码问题。您需要 CaptchaAI 来进行实际求解。
我可以将 Playwright 与所有验证码类型一起使用吗?
是的。 CaptchaAI 通过 API 处理解决问题 - Playwright 只需提取站点密钥并注入令牌。这适用于 reCAPTCHA、Turnstile、hCaptcha 和所有其他支持的类型。
Playwright 在验证码自动化方面比 Selenium 更好吗?
Playwright 的内置自动等待和更好的 API 设计使验证码工作流程更加可靠。两者的 CaptchaAI 集成是相同的。
相关指南
- 使用 Python 处理 Selenium 验证码
- 使用 Node.js 解决 Puppeteer CAPTCHA 问题
- 自动登录验证码处理