失眠网,内容丰富有趣,生活中的好帮手!
失眠网 > Python自动识别验证码

Python自动识别验证码

时间:2023-06-28 21:29:47

相关推荐

Python自动识别验证码

前言:这个是在网上找的代码修修改改之后发现还是蛮好用的。成功率在60%左右,虽然成功率虽然有点低,但是相对来说还是蛮可以的了。

import refrom PIL import Imageimport pytesseract# 自动识别验证码def get_pictures(driver):# 整个页面截图的图片存放路径driver.save_screenshot(r'D:\Honest\picture\poo1.png')# id是验证码在页面上的idpg = driver.find_element_by_id('codeImg')left = pg.location['x']top = pg.location['y']right = pg.size['width'] + leftheight = pg.size['height'] + topim = Image.open(r'D:\Honest\picture\poo1.png')image_obj = im.crop((left, top, right, height))# 验证码截图的图片存放路径image_obj.save(r'D:\Honest\picture\poo2.png')images = image_obj.convert("L") # 转灰度pixdata = images.load()w, h = images.size# 像素值threshold = 190# 遍历所有像素,大于阈值的为黑色for y in range(h):for x in range(w):if pixdata[x, y] < threshold:pixdata[x, y] = 0else:pixdata[x, y] = 255data = images.getdata()w, h = images.sizeblack_point = 0for x in range(1, w - 1):for y in range(1, h - 1):mid_pixel = data[w * y + x] # 中央像素点像素值if mid_pixel < 50: # 找出上下左右四个方向像素点像素值top_pixel = data[w * (y - 1) + x]left_pixel = data[w * y + (x - 1)]down_pixel = data[w * (y + 1) + x]right_pixel = data[w * y + (x + 1)]# 判断上下左右的黑色像素点总个数if top_pixel < 10:black_point += 1if left_pixel < 10:black_point += 1if down_pixel < 10:black_point += 1if right_pixel < 10:black_point += 1if black_point < 1:images.putpixel((x, y), 255)black_point = 0result = pytesseract.image_to_string(images) # 图片转文字resultj = re.sub(u"([^\u4e00-\u9fa5\u0030-\u0039\u0041-\u005a\u0061-\u007a])", "", result) # 去除识别出来的特殊字符result_four = resultj[0:4] # 只获取前4个字符# print(result_four) # 打印识别的验证码return result_four

调用例子:

from selenium import webdriverfrom mon_verification import get_pictures # 方法路径def test_a():driver = webdriver.Chrome()driver.get(r"")# 账号driver.find_element_by_name('loginname').send_keys('123')# 密码driver.find_element_by_name('password').send_keys('123')# 验证码 调用方法 get_pictures(self.driver)driver.find_element_by_id('code').send_keys(get_pictures(self.driver))if __name__ == '__main__':test_a()

如果觉得《Python自动识别验证码》对你有帮助,请点赞、收藏,并留下你的观点哦!

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。