1、使用ddddocr方法识别图片信息,python更高版本不再使用ddddocr库
import ddddocr
#获取验证码图片地址
code = driver.find_element(By.XPATH, element)
#下载图片
code.screenshot('code.png')
#分析图片中的数据
ocr = ddddocr.DdddOcr()
with open('code.png', 'rb') as f:
img_bytes = f.read()
res = ocr.classification(img_bytes)
#输入验证码
inputcode.send_keys(res)
2、使用Image、pytesseract库方法
from PIL import Image
import pytesseract
#定位验证码输入框位置
captcha = browser.find_element(By.XPATH, '//*[@id="code"]')
# 获取验证码图片位置
captcha_element = browser.find_element(By.XPATH, '//form[@id="formLogin"]/div[3]/div/div/span/span/span[2]/img')
#获取正确的验证码,并输入
while(True):
#保存照片
captcha_element.screenshot('captcha.png')
# 从图片提取验证码
with Image.open('captcha.png') as captcha_image:
captcha_text = pytesseract.image_to_string(captcha_image)
#校验验证码,并输入
if len(captcha_text) == 5:
captcha.send_keys(captcha_text)
break
else:
# 重新获取验证码
captcha_element.click()
time.sleep(3)