reCAPTCHA v2 图像识别模拟点击(Selenium)
这篇教程用 Selenium 4 打开 Google 的 reCAPTCHA 演示页,在真实浏览器里完成图片题:读出题目和图片,交给 reCAPTCHA v2 图像识别(ReCaptchaV2Classification)判断该点哪几格,再模拟点击。和拿 token 的方式相比,这种方式在浏览器里真实完成验证,适合 token 通过率低的网站。
不想写代码可以直接用 浏览器插件,它就是基于同一个接口自动点击的。
pip install requests selenium pillowexport YESCAPTCHA_CLIENT_KEY=你的clientKey需要安装 Chrome。Selenium 4 会自动下载匹配的 chromedriver。
- 点复选框。 复选框在
title="reCAPTCHA"的 iframe 里,先切换进去,点#recaptcha-anchor。 - 切到题目的 iframe。 题目在另一个 iframe(title 包含 “challenge”)里。
- 读题目。
.rc-imageselect-desc-wrapper strong里加粗的文字就是要找的目标,例如 “traffic lights”。接口要的是题目 ID,用对照表把名称换成 ID(/m/015qff),见 题目 ID。浏览器界面用英文最方便对照。 - 取图片。 格子里的图片其实是同一张大图,取
td.rc-imageselect-tile img的src下载下来。9 格(3x3)缩放到 300×300,16 格(4x4)缩放到 450×450,转成 Base64。 - 识别。 调用
createTask,类型ReCaptchaV2Classification,传image、question。加上"confidence": 0.5,3x3 图片会一次返回所有符合的格子,不用再处理点完后刷新出来的小图。 - 点击。 返回的
objects是格子序号,从 0 开始、从左到右、从上到下,依次点击对应的td。 - 验证。 点
#recaptcha-verify-button。如果又出了新的一轮题目,回到第 3 步;题目窗口关闭就是通过了。 - 提交表单。 回到主页面点提交按钮。
"""Click through a reCAPTCHA v2 image challenge with Selenium 4 and ReCaptchaV2Classification.
Flow: open the page -> click the checkbox -> read the target name and the grid image ->ask YesCaptcha which tiles to click -> click them -> press Verify. Repeat if a new challenge appears.
Run: pip install requests selenium pillow export YESCAPTCHA_CLIENT_KEY=your_client_key python recaptcha_click_selenium.pyEach recognized image is charged (see the price list). reCAPTCHA's page structure can change;adjust the selectors below if a step stops working."""import base64import ioimport osimport time
import requestsfrom PIL import Imagefrom selenium import webdriverfrom selenium.webdriver.common.by import Byfrom selenium.webdriver.support import expected_conditions as ECfrom selenium.webdriver.support.wait import WebDriverWait
CLIENT_KEY = os.environ["YESCAPTCHA_CLIENT_KEY"]PAGE_URL = "https://www.google.com/recaptcha/api2/demo"
# Target names shown in the challenge (English UI) -> question IDs.# Full list: https://docs.yescaptcha.com/en/tasks/recaptcha-classification/QUESTION_IDS = { "taxis": "/m/0pg52", "bus": "/m/01bjv", "buses": "/m/01bjv", "motorcycles": "/m/04_sv", "tractors": "/m/013xlm", "chimneys": "/m/01jk_4", "crosswalks": "/m/014xcs", "traffic lights": "/m/015qff", "bicycles": "/m/0199g", "parking meters": "/m/015qbp", "cars": "/m/0k4j", "bridges": "/m/015kr", "boats": "/m/019jd", "palm trees": "/m/0cdl1", "mountains or hills": "/m/09d_r", "fire hydrants": "/m/01pns0", "a fire hydrant": "/m/01pns0", "stairs": "/m/01lynh",}
def classify(image_b64, question): task = {"type": "ReCaptchaV2Classification", "image": image_b64, "question": question, "confidence": 0.5} data = requests.post( "https://api.yescaptcha.com/createTask", json={"clientKey": CLIENT_KEY, "task": task}, timeout=30, ).json() if data.get("errorId"): raise RuntimeError(f"{data.get('errorCode')}: {data.get('errorDescription')}") return data["solution"] # synchronous: the solution comes back right away
def grid_image_b64(url, size): """Download the challenge image and scale it to the standard size (300 for 3x3, 450 for 4x4).""" img = Image.open(io.BytesIO(requests.get(url, timeout=30).content)).convert("RGB") img = img.resize((size, size)) buf = io.BytesIO() img.save(buf, format="JPEG") return base64.b64encode(buf.getvalue()).decode()
driver = webdriver.Chrome()wait = WebDriverWait(driver, 15)try: driver.get(PAGE_URL)
# 1. Click the checkbox (inside the "reCAPTCHA" iframe) wait.until(EC.frame_to_be_available_and_switch_to_it((By.CSS_SELECTOR, 'iframe[title="reCAPTCHA"]'))) wait.until(EC.element_to_be_clickable((By.ID, "recaptcha-anchor"))).click() driver.switch_to.default_content()
# 2. Switch to the challenge iframe and solve rounds until it closes wait.until(EC.frame_to_be_available_and_switch_to_it( (By.XPATH, '//iframe[contains(@title, "challenge")]'))) for _ in range(5): target = wait.until(EC.presence_of_element_located( (By.CSS_SELECTOR, ".rc-imageselect-desc-wrapper strong"))).text.strip().lower() question = QUESTION_IDS.get(target) if not question: print("unsupported target, reloading:", target) driver.find_element(By.ID, "recaptcha-reload-button").click() time.sleep(2) continue tiles = driver.find_elements(By.CSS_SELECTOR, "td.rc-imageselect-tile") size = 450 if len(tiles) == 16 else 300 url = driver.find_element(By.CSS_SELECTOR, "td.rc-imageselect-tile img").get_attribute("src") solution = classify(grid_image_b64(url, size), question) for index in solution.get("objects", []): tiles[index].click() time.sleep(0.3) time.sleep(1) driver.find_element(By.ID, "recaptcha-verify-button").click() time.sleep(3) driver.switch_to.default_content() frame = driver.find_element(By.XPATH, '//iframe[contains(@title, "challenge")]') if not frame.is_displayed(): # challenge closed: passed break driver.switch_to.frame(frame)
driver.switch_to.default_content() driver.find_element(By.ID, "recaptcha-demo-submit").click() time.sleep(2) print("passed" if "Verification Success" in driver.page_source else "not passed")finally: driver.quit()- reCAPTCHA 的页面结构会更新,代码里的选择器失效时要按实际页面调整。
- 每次识别一张图都会扣点(价格见 reCAPTCHA v2 图像识别)。点击后验证失败的任务可以在 1 小时内 上报,申请返点。
- 遇到对照表里没有的题目,可以点刷新按钮换一题,或者联系客服增加支持。