验证码识别--封装版
import os
import time
def coding_path(path):
Base_Path = os.path.abspath(os.path.dirname(os.path.abspath(__file__)) +
'/..')
Base_image = os.path.join(Base_Path +
r'\PIC', path)
return Base_image
def time_():
# %Y_%m_%d_%H_%M_%S
file_name = time.strftime(
"%Y_%m_%d_%H_%M") +
".png"
return file_name
class Brouse:
def __init__(self):
self.fox = webdriver.Firefox()
def save_image(self):
"""
截图
:return:
"""
self.fox.save_screenshot(coding_path(time_()))
def location_(self, loc):
"""
:param loc:
:return:获取图片位置
"""
location = loc.location
return location
def location_size(self, loc):
"""
:param loc:
:return:获取图片大小
"""
location_size = loc.size
return location_size
def image_size(self, image):
"""截图验证码大小,根据实际修改"""
rangle = (int(self.location_(image)[
'x'] -
5), int(self.location_(image)[
'y'] -
5),
int(self.location_(image)[
'x'] + self.location_size(image)[
'width'] +
11),
int(self.location_(image)[
'y'] + self.location_size(image)[
'height'] +
7))
return rangle
def crop_image(self):
"""
:return: 识别截图验证码
"""
ocr = DdddOcr()
file_image = open(coding_path(time_()),
'rb')
result = ocr.classification(file_image.read())
return result
def eles_crop_image(self, ele, num):
"""
元素组截图定位
:param ele:
:param num:
:return:
"""
pic = self.fox.find_elements_by_xpath(ele)[num]
sleep(
1)
# 保存截图,调用时间戳
self.save_image()
# 获取位置
self.location_(pic)
# 获取大小
self.location_size(pic)
# 确定所需要的图片大小
self.image_size(pic)
# 打开之前截图图片
image = Image.open(coding_path(time_()))
# 开始裁剪
image1 = image.crop(self.image_size(pic))
# 保存裁剪后的截图
image1.save(coding_path(time_()))
# 图片内容
number = self.crop_image()
while
1:
if len(number) <
3:
number = self.crop_image()
return number
break
return number
def Fox_test(self):
self.fox.get(
'https://d2.shopxo.vip/admin.php?s=admin/logininfo.html')
self.fox.find_element_by_xpath(
"//input[@name='accounts']").send_keys(
'admin')
self.fox.find_element_by_xpath(
"//input[@name='pwd']").send_keys(
'shopxo')
self.fox.find_element_by_xpath(
"//input[@name='verify']").send_keys(
self.eles_crop_image(
"//span[@class='am-input-group-btn']",
1))
self.fox.find_element_by_xpath(
"//*[text()='登录']").click()
self.fox.close()
if __name__ ==
'__main__':
Brouse().Fox_test()
