进行到这里,我们会发现我们的代码很多了,但是管理非常的混乱不清晰,没有逻辑结构。再继续进行下去的话,代码的管理会越来越乱,后期的维护成本会越来越高。对,停下来歇一下,调整代码结构,梳理思路再上路,权当温故而知新。
调整的基本思路:
①将通用的代码函数化,减少代码的重复率;
②将功能代码函数化调用;
③主功能调用各个功能函数,组件化。
基本结构如下图所示:
GitHub代码commits id:0bd2671
#!/bin/usr/env python3
# -*- coding: utf-8 -*-
# --------------------------------
# ProjectName:
# Author: Crisimple
# CreateTime: 2019/6/8 17:00
# FileName: register_code.py
# Description:
# Question:
# --------------------------------
from selenium import webdriver
import time
import random
from PIL import Image
from base_code_package.ShowapiRequest import ShowapiRequest
driver = webdriver.Chrome('./tools/chromedriver.exe')
# 浏览器初始化
def driver_init():
driver.get("http://www.5itest.cn/register")
driver.maximize_window()
time.sleep(5)
# 获取 element 信息
def get_element(id):
element = driver.find_element_by_id(id)
return element
# 获取随机数
def get_range():
number = ''.join(random.sample('123456789abcdefg', 8))
return number
# 获取注册页面中验证码部分的图片
def get_code_image(file_name):
driver.save_screenshot(file_name)
code_element = driver.find_element_by_id("getcode_num")
left = code_element.location['x']
top = code_element.location['y']
right = code_element.size['width'] + left
height = code_element.size['height'] + top
im = Image.open(file_name)
img = im.crop((left, top, right, height))
img.save(file_name)
# 解析图片验证码
def code_online(file_name):
# 解析验证码图片中的文字(用第三方的图片验证码识别接口 ShowApiRequest)
r = ShowapiRequest("http://route.showapi.com/184-4","48120","12c017278c0845c2bcda177212d2d2ac" )
r.addBodyPara("img_base64", "")
r.addBodyPara("typeId", "35")
r.addBodyPara("convert_to_jpg", "0")
r.addBodyPara("needMorePrecise", "0")
r.addFilePara("image", file_name) #文件上传时设置
res = r.post()
text = res.json()["showapi_res_body"]["Result"]
return text
# 主程序
def run_main():
user_name = get_range()
user_email = user_name + "@163.com"
file_name = "./image/code_image.png"
driver_init()
get_element("register_email").send_keys(user_email)
get_element("register_nickname").send_keys(user_name)
get_element("register_password").send_keys("Test@123")
get_code_image(file_name)
text = code_online(file_name)
get_element("captcha_code").send_keys(text)
get_element("register-btn").click()
driver.close()
if __name__ == "__main__":
run_main()