logo

Python自动化实战:Selenium+百度OCR破解网站登录验证码

作者:半吊子全栈工匠2025.10.10 16:52浏览量:30

简介:本文详细讲解如何使用Python的Selenium库实现网站自动登录,并结合百度文字识别(Baidu-AIP)服务破解验证码,提供从环境配置到完整代码实现的分步指南。

一、技术选型与原理说明

1.1 Selenium自动化测试框架

Selenium是一个开源的Web自动化测试框架,支持通过浏览器驱动(如ChromeDriver)模拟用户操作。其核心优势在于:

  • 跨浏览器支持(Chrome/Firefox/Edge)
  • 元素定位方式多样(ID/XPath/CSS选择器)
  • 支持JavaScript渲染页面
  • 提供丰富的API接口(点击/输入/等待等)

典型应用场景包括:

  • 自动化测试
  • 数据爬取
  • 重复性Web操作自动化

1.2 百度文字识别(Baidu-AIP)

百度文字识别是百度智能云提供的OCR服务,具有以下特点:

  • 高精度识别(支持中英文、数字、特殊字符)
  • 多场景适配(通用文字、网络图片、身份证等)
  • 快速响应(API调用平均耗时<1s)
  • 免费额度充足(每月500次免费调用)

验证码识别流程:

  1. 截取验证码图片
  2. 调用OCR接口
  3. 解析返回的文本结果
  4. 输入识别结果

二、环境准备与依赖安装

2.1 系统要求

  • Python 3.6+
  • Chrome浏览器(最新稳定版)
  • 稳定的网络连接

2.2 依赖库安装

  1. pip install selenium pillow baidu-aip requests

2.3 浏览器驱动配置

  1. 下载对应Chrome版本的ChromeDriver
  2. 解压后将路径添加到系统PATH
  3. 验证安装:
    1. from selenium import webdriver
    2. driver = webdriver.Chrome()
    3. driver.quit()

2.4 百度OCR服务开通

  1. 登录百度智能云控制台
  2. 创建文字识别应用
  3. 获取API Key和Secret Key
  4. 安装SDK:
    1. from aip import AipOcr
    2. APP_ID = '您的App ID'
    3. API_KEY = '您的API Key'
    4. SECRET_KEY = '您的Secret Key'
    5. client = AipOcr(APP_ID, API_KEY, SECRET_KEY)

三、核心功能实现

3.1 基础登录流程

  1. from selenium import webdriver
  2. from selenium.webdriver.common.by import By
  3. import time
  4. def basic_login(url, username, password):
  5. driver = webdriver.Chrome()
  6. try:
  7. driver.get(url)
  8. # 等待页面加载(显式等待更佳)
  9. time.sleep(2)
  10. # 定位元素并输入
  11. driver.find_element(By.ID, 'username').send_keys(username)
  12. driver.find_element(By.ID, 'password').send_keys(password)
  13. # 点击登录按钮
  14. driver.find_element(By.ID, 'loginBtn').click()
  15. # 验证登录结果
  16. assert 'dashboard' in driver.current_url
  17. print("登录成功")
  18. except Exception as e:
  19. print(f"登录失败: {str(e)}")
  20. finally:
  21. driver.quit()

3.2 验证码处理模块

3.2.1 验证码截取

  1. from PIL import Image
  2. import numpy as np
  3. def capture_captcha(driver, element_locator):
  4. """截取验证码元素并保存为图片"""
  5. captcha_element = driver.find_element(*element_locator)
  6. location = captcha_element.location
  7. size = captcha_element.size
  8. # 截取整个屏幕
  9. screenshot = driver.get_screenshot_as_png()
  10. screenshot = Image.open(io.BytesIO(screenshot))
  11. # 裁剪验证码区域
  12. left = location['x']
  13. top = location['y']
  14. right = left + size['width']
  15. bottom = top + size['height']
  16. captcha = screenshot.crop((left, top, right, bottom))
  17. # 保存临时文件(实际可优化为内存处理)
  18. captcha.save('captcha.png')
  19. return 'captcha.png'

3.2.2 百度OCR识别

  1. def recognize_captcha(image_path):
  2. """调用百度OCR识别验证码"""
  3. with open(image_path, 'rb') as f:
  4. image = f.read()
  5. # 通用文字识别(高精度版)
  6. result = client.basicAccurate(image)
  7. if 'words_result' in result:
  8. # 提取识别结果(简单场景下直接取第一个)
  9. captcha_text = result['words_result'][0]['words']
  10. return captcha_text.strip()
  11. else:
  12. raise Exception("OCR识别失败: " + str(result))

3.3 完整登录实现

  1. from selenium.webdriver.common.by import By
  2. from selenium.webdriver.support.ui import WebDriverWait
  3. from selenium.webdriver.support import expected_conditions as EC
  4. def auto_login_with_captcha(url, username, password):
  5. driver = webdriver.Chrome()
  6. try:
  7. driver.get(url)
  8. # 输入用户名密码
  9. WebDriverWait(driver, 10).until(
  10. EC.presence_of_element_located((By.ID, 'username'))
  11. ).send_keys(username)
  12. driver.find_element(By.ID, 'password').send_keys(password)
  13. # 处理验证码
  14. captcha_locator = (By.ID, 'captchaImg')
  15. img_path = capture_captcha(driver, captcha_locator)
  16. captcha_text = recognize_captcha(img_path)
  17. print(f"识别结果: {captcha_text}")
  18. # 输入验证码
  19. driver.find_element(By.ID, 'captcha').send_keys(captcha_text)
  20. # 提交登录
  21. driver.find_element(By.ID, 'loginBtn').click()
  22. # 验证结果
  23. WebDriverWait(driver, 10).until(
  24. EC.url_contains('dashboard')
  25. )
  26. print("自动化登录成功")
  27. except Exception as e:
  28. print(f"发生错误: {str(e)}")
  29. finally:
  30. driver.quit()

四、优化与进阶

4.1 异常处理机制

  1. def robust_login():
  2. max_retries = 3
  3. for attempt in range(max_retries):
  4. try:
  5. auto_login_with_captcha(url, username, password)
  6. break
  7. except Exception as e:
  8. if attempt == max_retries - 1:
  9. raise
  10. print(f"第{attempt+1}次尝试失败,重试...")
  11. time.sleep(2)

4.2 识别率提升技巧

  1. 预处理验证码图片:
    ```python
    from PIL import ImageEnhance, ImageFilter

def preprocess_image(image_path):
img = Image.open(image_path)

  1. # 增强对比度
  2. enhancer = ImageEnhance.Contrast(img)
  3. img = enhancer.enhance(2)
  4. # 二值化处理
  5. img = img.convert('1')
  6. # 降噪
  7. img = img.filter(ImageFilter.MedianFilter())
  8. img.save('processed_captcha.png')
  9. return 'processed_captcha.png'
  1. 2. 多模型组合识别:
  2. ```python
  3. def hybrid_recognition(image_path):
  4. try:
  5. # 先尝试高精度识别
  6. return client.basicAccurate(open(image_path, 'rb').read())
  7. except:
  8. # 失败后使用通用识别
  9. return client.basicGeneral(open(image_path, 'rb').read())

4.3 性能优化建议

  1. 使用无头模式减少资源消耗:
    ```python
    from selenium.webdriver.chrome.options import Options

options = Options()
options.add_argument(‘—headless’)
driver = webdriver.Chrome(options=options)

  1. 2. 实现验证码缓存机制:
  2. ```python
  3. import hashlib
  4. captcha_cache = {}
  5. def get_cached_captcha(image_bytes):
  6. img_hash = hashlib.md5(image_bytes).hexdigest()
  7. if img_hash in captcha_cache:
  8. return captcha_cache[img_hash]
  9. else:
  10. result = recognize_captcha(image_bytes)
  11. captcha_cache[img_hash] = result
  12. return result

五、法律与伦理考量

  1. 合规使用

    • 仅用于授权测试
    • 遵守目标网站的robots.txt
    • 控制请求频率(建议≥3秒/次)
  2. 验证码识别边界

    • 禁止用于破解付费服务
    • 不得绕过安全验证机制
    • 尊重网站的反爬策略
  3. 数据安全

    • 敏感信息脱敏处理
    • 避免存储用户凭证
    • 使用HTTPS协议通信

六、完整示例代码

  1. # 完整实现请参考上述模块组合
  2. # 实际使用时需要替换:
  3. # 1. 目标网站的元素定位方式
  4. # 2. 百度OCR的认证信息
  5. # 3. 异常处理逻辑
  6. if __name__ == "__main__":
  7. # 配置参数
  8. CONFIG = {
  9. 'login_url': 'https://example.com/login',
  10. 'username': 'test_user',
  11. 'password': 'secure_password',
  12. 'max_retries': 3
  13. }
  14. # 执行自动化登录
  15. try:
  16. robust_login(CONFIG)
  17. except Exception as e:
  18. print(f"自动化流程终止: {str(e)}")

七、总结与展望

本文实现的Selenium+百度OCR自动化登录方案具有以下优势:

  1. 高可扩展性:通过修改定位器即可适配不同网站
  2. 高识别率:百度OCR在清晰验证码场景下可达95%+准确率
  3. 低成本:免费额度可满足中小规模需求

未来改进方向:

  1. 集成深度学习模型处理复杂验证码
  2. 实现分布式任务队列
  3. 添加日志分析与可视化模块

建议开发者在实际应用中:

  1. 添加详细的日志记录
  2. 实现邮件/短信报警机制
  3. 定期更新浏览器驱动
  4. 监控OCR服务调用情况

通过合理使用自动化技术,可以显著提升工作效率,但必须始终遵守法律法规和道德准则。

相关文章推荐

发表评论

活动