【Python爬虫】图片验证码的处理

什么是图片验证码?

验证码(CAPTCHA)是"Completely Automated Public Turing test to tell Computers and HumansApart"(全自动区分计算机和人类的图灵测试)的缩写,是一种区分用户是计算机还是人的公共全自动程序。

图片验证码的处理方案

  1. 手动输入(input)这种方法仅限于登录一次就可持续使用的情况
  2. 图像识别引擎解析使用光学识别引擎处理图片中的数据,目前常用于图片数据提取,较少用于验证码处理
  3. 打码平台爬虫常用的验证码解决方案

图片识别引擎

OCR(Optical Character Recognition)是指使用扫描仪或数码相机对文本资料进行扫描成图像文件,然后对图像文件进行分析处理,自动识别获取文字信息及版面信息的软件。

什么是tesseract

Tesseract,一款由HP实验室开发由Google维护的开源OCR引擎,特点是开源,免费,支持多语言,多

平台。

项目地址:https:/github.com/tesseract-ocr/tesseract

图片识别引擎环境的安装

-mac环境下直接执行命令:brew install --with-training-tools tesseract

-windows环境下的安装可以通过exe安装包安装,下载地址:Home · UB-Mannheim/tesseract Wiki · GitHub

安装完成后记得将Tesseract 执行文件的目录加入到PATH中,方便后续调用。

配置教程:超详细解决pytesseract.pytesseract.TesseractNotFoundError: tesseract is not installed or it's not in yo... - 简书 (jianshu.com)

  • 从第5步开始看
  • 其中第9步的修改py文件的文件路径在报错里可以找到(这个报错在下面的"使用代码"执行后可以得到)
  • 当然,如果配置成功就没有报错了

-linux环境下的安装:sudo apt-get install tesseract-ocr

Python库的安装

# PIL用于打开图片文件
pip install pillow
# pytesseract模块用于从图片中解析数据
pip install pytesseract

使用代码

python 复制代码
# 图像识别引擎
from PIL import Image
import pytesseract

im = Image.open("图片路径")
result = pytesseract.image_to_string(im)
print(result)

其他OCR平台

微软Azure 图像识别:https://azure.microsoft.com/zh-cn/services/cognitive-services/computer-vision/
阿里云图文识别:https://www.aliyun.com/product/cdi/
腾讯OCR文字识别:https://cloud.tencent.com/product/ocr

国内的识别引擎对于中文的支持会更好

常见的验证码的种类

url地址不变,验证码不变

这是验证码里面非常简单的一种类型,对应的只需要获取验证码的地址,然后请求,通过打码平台识别即可

url地址不变,验证码变化

这种验证码的类型是更加常见的一种类型,对于这种验证码,大家需要思考:在登录的过程中,假设我输入的验证码是对的,对方服务器是如何判断当前我输入的验证码是显示在我屏幕上的验证码,而不是其他的验证码呢?

在获取网页的时候,请求验证码,以及提交验证码的时候,对方服务器肯定通过了某种手段验证我之前获取的验证码和最后提交的验证码是同一个验证码,那这个手段是什么手段呢?

很明显,就是通过cookie来实现的,所以对应的,在请求页面,请求验证码,提交验证码的到时候需要保证cookie的一致性,对此可以使用requests.session来解决

打码平台------2Captcha的使用

笔者自己使用的,需要付费;可自行使用其他平台

网址:https://2captcha.com/zh

以下教程来源:Python验证码破解程序------在线识别验证码和2Captcha的Anti Captcha API

pip3 install 2captcha-python

TwoCaptcha类实例可按照如下方法创建:

python 复制代码
from twocaptcha import TwoCaptcha

solver = TwoCaptcha('YOUR_API_KEY')
# 您还能为已创建的实例设置选项:
config = {
            'server':           '2captcha.com',
            'apiKey':           'YOUR_API_KEY',
            'softId':            123,
            'callback':         'https://your.site/result-receiver',
            'defaultTimeout':    120,
            'recaptchaTimeout':  600,
            'pollingInterval':   10,
        }
solver = TwoCaptcha(**config)

实例选项

选项 默认值 说明
服务器 '2captcha.com' API服务器。您可以将注册账户设置为'rucaptcha.com'。
softId - 您将在2Captcha软件目录发布后获得软件ID
回调函数 - 验证码识别结果会发送至网络服务器URL,但应先在账户的pingback设置中注册URL
defaultTimeout 120 除reCAPTCHA外的验证码的轮询超时时间(秒),用于判定模块尝试从res.phpAPI端点获得答案的时间
recaptchaTimeout 600 reCAPTCHA的轮询超时时间(秒),用于判定模块尝试从res.phpAPI端点获得答案的时间
pollingInterval 10 res.phpAPI端点发送请求的间隔时间(秒),不建议设置在5秒以内

重要提示 :一旦回调函数确定用于TwoCaptcha实例,那么所有方法都只返回验证码ID,无法通过轮询API获得结果。结果将发送至回调URL。请通过getResult方法进行人工破解。

您在提交图片验证码时可提出额外选项,以便2Captcha的员工能够正确破解。

验证码选项

选项 默认值 说明
numeric 0 判定验证码是否由数字或其他符号组成,详情请见API文档
minLength 0 最小答案长度
maxLength 0 最大答案长度
phrase 0 判定答案是否由多个词语组成
caseSensitive 0 判定答案是否区分大小写
calc 0 确定验证码需要计算
lang - 确定验证码语言,见可用语言列表
hintImg - 所有验证码员工可见的提示图片
hintText - 员工可见的验证码提示或任务文字

验证码类别

您可以利用以下方法绕过normal captcha(带有扭曲文字的图片)。这个方法也可用于识别图片上的任何文字。

result = solver.normal('path/to/captcha.jpg', param1=..., ...)

这种方法可用于绕过需要回答清晰文字问题的验证码。

result = solver.text('If tomorrow is Saturday, what day is today?', param1=..., ...)

此方法可破解reCAPTCHA V2,并获得令牌实现绕过保护。

result = solver.recaptcha(sitekey='6Le-wvkSVVABCPBMRTvw0Q4Muexq1bi0DJwx_mJ-',
  url='https://mysite.com/page/with/recaptcha',
  param1=..., ...)

此方法利可破解reCAPTCHA V3,并返回令牌。

result = solver.recaptcha(sitekey='6Le-wvkSVVABCPBMRTvw0Q4Muexq1bi0DJwx_mJ-',
  url='https://mysite.com/page/with/recaptcha',
  version='v3',
  param1=..., ...)

FunCaptcha(Arkoselabs)破解方法,并返回令牌。

result = solver.funcaptcha(sitekey='6Le-wvkSVVABCPBMRTvw0Q4Muexq1bi0DJwx_mJ-',
  url='https://mysite.com/page/with/funcaptcha',
  param1=..., ...)

此方法可破解GeeTest拼图验证码,并返回一组JSON格式的令牌。

result = solver.geetest(gt='f1ab2cdefa3456789012345b6c78d90e',
  challenge='12345678abc90123d45678ef90123a456b',
  url='https://www.site.com/page/',
  param1=..., ...)

此方法可破解hCaptcha,并返回可以绕过验证码的令牌。

result = solver.hcaptcha(sitekey='10000000-ffff-ffff-ffff-000000000001',
  url='https://www.site.com/page/', 
  param1=..., ...)

通过令牌形式破解KeyCaptcha。

result = solver.keycaptcha(s_s_c_user_id=10,
    s_s_c_session_id='493e52c37c10c2bcdf4a00cbc9ccd1e8',
    s_s_c_web_server_sign='9006dc725760858e4c0715b835472f22-pz-',
    s_s_c_web_server_sign2='2ca3abe86d90c6142d5571db98af6714',
    url='https://www.keycaptcha.ru/demo-magnetic/', 
    param1=..., ...)

以令牌形式绕过Capy拼图验证码。

result = solver.capy(sitekey='PUZZLE_Abc1dEFghIJKLM2no34P56q7rStu8v',
  url='http://mysite.com/',
  api_server='https://jp.api.capy.me/',
  param1=..., ...)

Grid法最初名为Old reCAPTCHA V2法,先在图中画好网格,点击特定网格框,以绕过任何类型的验证码。这种方法会返回方框数。

result = solver.grid('path/to/captcha.jpg', param1=..., ...)

Canvas法需要围着图中物体画一条线。这种方法会返回一组点坐标,用于绘制多边形。

result = solver.canvas('path/to/captcha.jpg', param1=..., ...)

ClickCaptcha会返回验证码图片的点坐标,若您需要点击图片的特定点,就可以使用这种方法。

result = solver.coordinates('path/to/captcha.jpg', param1=..., ...)

这种方法可破解需要旋转物体的验证码,主要用于绕过FunCaptcha。它会返回旋转角度。

result = solver.rotate('path/to/captcha.jpg', param1=..., ...)

一些方法&&操作

send / getResult

上述方法可用于人工提交验证码和答案轮询。

python 复制代码
import time
. . . . . 

id = solver.send(file='path/to/captcha.jpg')
time.sleep(20)

code = solver.get_result(id)

balance

以此方法获取账户余额:balance = solver.balance()

report

以此方法报告验证码答案之优劣。

solver.report(id, True) # captcha solved correctly
solver.report(id, False) # captcha solved incorrectly

如发生错误,验证码破解程序会提示异常。妥善处理这类情况很重要。我们推荐使用try/except来处理异常。

python 复制代码
Try:
    result = solver.text('If tomorrow is Saturday, what day is today?')
Except ValidationException as e:
    # invalid parameters passed
  print(e)
Except NetworkException as e:
  # network error occurred
  print(e)
Except ApiException as e:
  # api respond with error
  print(e)
Except TimeoutException as e:
  # captcha is not solved so far
  print(e)

代理

您可以将代理作为参数应用于以下方法:recaptcha、funcaptcha、geetest。代理将被转发至API以破解验证码。

proxy={
    'type': 'HTTPS',
    'uri': 'login:password@IP_address:PORT'
}

异步回调

您也可以利用asyncio进行异步回调。

python 复制代码
import asyncio
import concurrent.futures
from twocaptcha import TwoCaptcha

captcha_result = await captchaSolver(image)

async def captchaSolver(image):
    loop = asyncio.get_running_loop()
    with concurrent.future.ThreadPoolExecutor() as pool:
        result = await loop.run_in_executor(pool, lambda: TwoCaptcha(API_KEY).normal(image))
        return result

使用selenium

完整教程请看:Selenium验证码求解器:如何使用反验证码2Captcha服务自动绕过reCAPTCHA、hCaptcha、Cloudflare、Arkose labs以及任何验证码

python 复制代码
from selenium.webdriver.common.by import By
from twocaptcha import TwoCaptcha
from selenium.webdriver.chrome.service import Service as ChromeService
from webdriver_manager.chrome import ChromeDriverManager
from selenium import webdriver

# 实例化 WebDriver
driver = webdriver.Chrome(service=ChromeService(ChromeDriverManager().install()))

# 加载目标页面
captcha_page_url = "https://recaptcha-demo.appspot.com/recaptcha-v2-checkbox.php"
driver.get(captcha_page_url)

# 解决验证码问题
print("Solving Captcha")
solver = TwoCaptcha("2CAPTCHA_API_KEY")
response = solver.recaptcha(sitekey='SITE_KEY', url=captcha_page_url)
代码 = response['code']
print(f "Successfully solved the Captcha. The solve code is {code}")

# 设置已解决的验证码
recaptcha_response_element = driver.find_element(By.ID, 'g-recaptcha-response')
driver.execute_script(f'arguments[0].value = "{code}";', recaptcha_response_element)

# 提交表单
submit_btn = driver.find_element(By.CSS_SELECTOR, 'button[type="submit"]')
submit_btn.click()

# 暂停执行,以便在关闭驱动程序前查看提交后的屏幕情况
输入("按回车键继续")
driver.close()

2CAPTCHA_API_KEYSITE_KEY 替换为它们的值,然后运行代码,验证码将被破解,你将看到成功界面。

简单示例

python 复制代码
from twocaptcha import TwoCaptcha
import time

solver = TwoCaptcha('your own key')
config = {
            'server':           '2captcha.com',
            'apiKey':           'your own key',
            'defaultTimeout':    120,
            'recaptchaTimeout':  600,
            'pollingInterval':   10,
        }
solver = TwoCaptcha(**config)
result = solver.normal('captcha.jpg', caseSensitive=1)
id = solver.send(file='captcha.jpg')
time.sleep(20)
code = solver.get_result(id)
print(code)
相关推荐
JUNAI_Strive_ving2 分钟前
番茄小说逆向爬取
javascript·python
彤银浦3 分钟前
python学习记录7
python·学习
落落落sss6 分钟前
MybatisPlus
android·java·开发语言·spring·tomcat·rabbitmq·mybatis
简单.is.good24 分钟前
【测试】接口测试与接口自动化
开发语言·python
Yvemil743 分钟前
MQ 架构设计原理与消息中间件详解(二)
开发语言·后端·ruby
程序员是干活的44 分钟前
私家车开车回家过节会发生什么事情
java·开发语言·软件构建·1024程序员节
Envyᥫᩣ1 小时前
Python中的自然语言处理:从基础到高级
python·自然语言处理·easyui
哪 吒1 小时前
华为OD机试 - 几何平均值最大子数(Python/JS/C/C++ 2024 E卷 200分)
javascript·python·华为od
我是陈泽1 小时前
一行 Python 代码能实现什么丧心病狂的功能?圣诞树源代码
开发语言·python·程序员·编程·python教程·python学习·python教学
hakesashou1 小时前
python全栈开发是什么?
python