selenium破解数字验证码

搞了半天,总算弄出来了,识别率还可以,普通的数字验证码

from selenium import webdriver
from PIL import Image
import pytesseract
import PIL.ImageOps
import time

driver = webdriver.Chrome()

url = ''
driver.implicitly_wait(10)
driver.get(url)
driver.find_element_by_xpath('//*[@id="1_5"]').click()  # 点击第三个
driver.find_element_by_xpath('//*[@id="4_organname"]').send_keys('代理')  # 输入代理

driver.save_screenshot('f.jpg')  # 获取网页的截图
imgelement = driver.find_element_by_id('cx5')  # 通过id定位验证码
location = imgelement.location  # 获取验证码的x,y轴
size = imgelement.size  # 获取验证码的长宽
rangle = (int(location['x']),
          int(location['y']),
          int(location['x']) + size['width'],
          int(location['y']) + size['height'],)  # 我们需要截取的验证码坐标

i = Image.open('f.jpg')#整张网页
verifycodeimage = i.crop(rangle)  # 从网页截图截取验证码区域
verifycodeimage.save('f2.jpg')
im = Image.open('f2.jpg')#验证码区域
im.show()

#、二值化处理

# 二值化是图像分割的一种常用方法。在二值化图象的时候把大于某个临界灰度值的像素灰度设为灰度极大值,
# 把小于这个值的像素灰度设为灰度极小值,从而实现二值化(一般设置为0-1)。根据阈值选取的不同,二值化的算法分为固定阈值和自适应阈值,
# 这里选用比较简单的固定阈值。把像素点大于阈值的设置,1,小于阈值的设置为0。生成一张查找表,再调用point()进行映射。
def initTable(threshold=140):
    table = []
    for i in range(256):
        if i < threshold:
            table.append(0)
        else:
            table.append(1)
    return table


im = im.convert('L')#转换为灰色图像
binaryImage = im.point(initTable(), '1')
im1 = binaryImage.convert('L')
im2 = PIL.ImageOps.invert(im1)
im3 = im2.convert('1')
im4 = im3.convert('L')
# 将图片中字符裁剪保留
box = (5, 2, 57, 17)#这个参数改了半天
region = im4.crop(box)
# 将图片字符放大
out = region.resize((120, 38))
testdata_dir_config = '--tessdata-dir "C:\\Program Files\\Tesseract-OCR\\tessdata"'
out.show()
asd = pytesseract.image_to_string(out, config=testdata_dir_config)  # 拿到验证码
textcode = asd.replace(' ', '')  # 过滤空格
print(textcode)
time.sleep(2)
driver.find_element_by_xpath('//*[@id="valcode4"]').send_keys(textcode)  # 输入验证码
driver.find_element_by_xpath('//*[@id="tab_1_5"]/ul/li[4]/img[1]').click()  # 点击查询

猜你喜欢

转载自www.cnblogs.com/z-x-y/p/9037920.html