selenium自动化测试封装

版权声明:若转载请指明出处 https://blog.csdn.net/qq_24790545/article/details/82495102

coding=utf-8

import tkinter
import os,re
import random
import string
import time
from datetime import timedelta, date
from re import sub

from selenium import webdriver
from selenium.common.exceptions import TimeoutException
from selenium.webdriver.common.by import By
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.support import ui
from selenium.webdriver.support.ui import WebDriverWait

from config import globaDB
from config.orgCode import CreditIdentifier
from public.common.log import Log
from config.orgCode import CreditIdentifier
from config.orgCode import area_dict
from config.orgCode import id_code_list, check_code_list, orgList

success = “SUCCESS ”
fail = “FAIL ”
logger = Log()

from config import globaVar

OVER_TIME = 5
currtime = time.strftime(‘%Y%m%d%H%M’, time.localtime(time.time()))

class Beans(object):
def init(self, browser=’ff’, remoteAddress=None):
“””
remote consle:
dr = PySelenium(‘RChrome’,’127.0.0.1:8080’)
“”“

def __new__(cls, *args, **kw):
    """
    使用单例模式将类设置为运行时只有一个实例,在其他Python类中使用基类时,
    可以创建多个对象,保证所有的对象都是基于一个浏览器
    """
    if not hasattr(cls, '_instance'):
        orig = super(Beans, cls)
        cls._instance = orig.__new__(cls, *args, **kw)
    return cls._instance

def driver(self):
    '''init 返回driver'''
    return self.driver()



def printTitle(self, css):
    '''简化输入,需要传入css和具体的值'''
    t1 = time.time()
    try:
        self.elementWait(css)

        val = self.driver.find_element_by_css_selector(css).get_attribute("title")
        return val
        self.my_print_info("{0} ,web elenium <{1}> title Spend {1} seconds".format(success, css, time.time() - t1))

    except Exception:
        self.my_print_error("{0} Unable to type element: <{1}> content: {2}, Spend {3} seconds".format(fail,
                                                                                                       css,
                                                                                                       time.time() - t1))
        raise

def clickTab(self, css):
    '''简化输入,需要传入css和具体的值'''

    t1 = time.time()
    try:
        self.elementWait(css)
        el = self.driver.find_element_by_css_selector(css)
        el.send_keys(Keys.TAB)
        self.my_print_info("{0} Typed element: <{1}>  Spend {2} seconds".format(success,
                                                                                             css,
                                                                                             time.time() - t1))
    except Exception:
        self.my_print_error("{0} Unable to type element: <{1}> content: {2}, Spend {3} seconds".format(fail,
                                                                                                       css,
                                                                                                       time.time() - t1))
        raise

def clickEnter(self, css):
    '''简化输入,需要传入css和具体的值'''

    t1 = time.time()
    try:
        self.elementWait(css)
        el = self.driver.find_element_by_css_selector(css)
        el.send_keys(Keys.ENTER)
        self.my_print_info("{0} Typed element: <{1}>  Spend {2} seconds".format(success,
                                                                                             css,
                                                                                             time.time() - t1))
    except Exception:
        self.my_print_error("{0} Unable to type element: <{1}> , Spend {2} seconds".format(fail,
                                                                                                       css,
                                                                                                       time.time() - t1))
        raise

def browerInput(self, css, text):
    """
    Operation input box.

    Usage:
    driver.type("id=kw","selenium")
    """
    t1 = time.time()
    try:
        self.elementWait(css)
        el = self.driver.find_element_by_css_selector(css)
        el.send_keys(text)
        self.my_print_info("{0} Typed element: <{1}> content: {2}, Spend {3} seconds".format(success,
                                                                                        css, text,
                                                                                        time.time() - t1))
    except Exception:
        self.my_print_error("{0} Unable to type element: <{1}> content: {2}, Spend {3} seconds".format(fail,
                                                                                                 css, text,
                                                                                                 time.time() - t1))
        raise


def browerClear(self, css):
    '''模拟清除,需要传入css'''

    t1 = time.time()
    try:
        self.elementWait(css)
        el = self.driver.find_element_by_css_selector(css)
        el.clear()
        self.my_print_info("{0} Element <{1}> empty  : , Spend {2} seconds".format(success,css,time.time() - t1))
    except Exception:
        self.my_print_error("Element empty exception ")
        raise


def browerClick(self, css):
    '''用于简化输入,模拟点击'''


    t1 = time.time()
    try:
        self.elementWait(css)
        el = self.driver.find_element_by_css_selector(css)
        el.click()
        self.my_print_info("{0} elenium <{1}> : , Spend {2} seconds".format(success,css,time.time() - t1))
    except Exception:
        self.my_print_info("Element empty exception ")
        raise

def umlogin(self, name, passwd, url):
    '''此方法用于um登录,输入用户名、密码、路径'''
    BASE_URL = url
    username = name
    password = passwd


    self.driver = webdriver.Chrome()
    self.driver.implicitly_wait(10)
    self.driver.get(BASE_URL)
    time.sleep(2)
    self.driver.maximize_window()
    self.ifrmaeSwitch("#paLoginWrap")
    self.browerClear("#loginForm #username")
    self.browerInput("#loginForm #username", username)

    self.driver.find_element_by_css_selector("#loginForm #username").send_keys(Keys.TAB)
    self.clickTab("#loginForm #username")

    self.browerInput("#loginForm #password", password)

    self.browerClick("#loginForm > input.btn_primary")

    self.driver.implicitly_wait(3)
    self.is_not_visible("body > div.panel.window.messager-window.message-loading > div")

def loginNoRUL(self, name, passwd):
    '''此方法用于无路径登录,即退出后的登录主要用于审核时,输入用户名和密码'''
    self.ifrmaeSwitch("#paLoginWrap")

    self.browerClear("#loginForm #username")
    self.browerInput("#loginForm #username",name)

    self.clickTab("#loginForm #username")

    self.browerInput("#loginForm #password",passwd)

    self.browerClick("#loginForm > input.btn_primary")

    self.driver.implicitly_wait(3)

def gylogin(self, name, passwd, url):
    '''此方法用于柜员登录,输入用户名、密码、路径'''

    BASE_URL = url
    username = name
    # username = '15591'
    password = passwd

    self.driver = webdriver.Chrome()
    self.driver.implicitly_wait(10)
    self.driver.get(BASE_URL)
    self.driver.maximize_window()
    self.driver.implicitly_wait(5)
    self.browerClear("#USER_CODE")
    self.browerInput("#USER_CODE",username)
    self.browerClear("#TRD_PWD")
    self.browerInput("#TRD_PWD",password)
    self.browerClick("#loginBtn")
    self.driver.implicitly_wait(10)


def loginadmin(self, url):
    '''此方法用于管理员,输入用户名、密码、路径'''
    if globaVar.um == '1' and globaVar.event == 'fat':

        self.umlogin('umrunner', 'aaaaa888', globaVar.faturl)
    elif globaVar.um == '1' and globaVar.event == 'uat':

        self.umlogin('GUANLI639', '123321', "http://10.25.168.170:30073/opp_webapp/")

    elif globaVar.um == '0' and globaVar.event == 'fat':
        self.gylogin('9999', '888888', globaVar.faturl)
    else:
        BASE_URL = "http://10.25.168.170:30073/opp_webapp/"
        username = '21685'
        passwd = '123321'
        self.driver = webdriver.Chrome()
        self.driver.implicitly_wait(10)
        self.driver.get(BASE_URL)
        self.driver.maximize_window()
        self.driver.implicitly_wait(5)
        self.browerClear("#USER_CODE")
        self.browerInput("#USER_CODE", username)
        self.browerClear("#TRD_PWD")
        self.browerInput("#TRD_PWD", passwd)
        self.browerClick("#loginBtn")
        self.driver.implicitly_wait(10)
        self.driver.implicitly_wait(10)
        time.sleep(2)

def login(self, url):
    """
    启动浏览器
    :param url: 测试地址
    :param driver_name: 在启动时设置浏览器的类型
    :return:
    """

    if globaVar.um == '1' and globaVar.event == 'fat':

        self.umlogin(globaVar.umname, globaVar.umpass, globaVar.faturl)
    elif globaVar.um == '1' and globaVar.event == 'loc':
        self.gylogin('15591', '123321', globaVar.local)
    elif globaVar.um == '1' and globaVar.event == 'uat':
        url = 'http://10.25.168.170:30073/opp_webapp/'
        # umname = '3070SHOULI843'
        umpass = '123321'
        self.umlogin('3070SHOULI843', umpass, url)

    # 调用is not visivle方法来
    self.is_not_visible("body > div.panel.window.messager-window.message-loading > div")
    self.is_element_exist('#POST_NAME')

    # 用于登录后弹出的“打开读卡器失败,请检查读卡器状态!”点击确定
    self.popboxinfo()

def login12306(self, url):
    """
    启动浏览器
    :param url: 测试地址
    :param driver_name: 在启动时设置浏览器的类型
    :return:
    """
    self.driver = webdriver.Chrome()
    self.driver.maximize_window()
    self.driver.implicitly_wait(10)
    self.driver.get(url)


def clikcOpenccount(self):
    """
    识别个人开户并切换ifrome
    """
    time.sleep(1)
    self.ifrmaeSwitch('iframe[src*=cust]')

    self.browerClick("#custOpenAcctBtn")

    time.sleep(3)


    self.ifrmaeSwitchDefault("#openAccountTab0 > iframe")
    time.sleep(1)
    self.is_not_visible("body > div.panel.window.messager-window.message-loading > div")


def popboxinfo(self):
    self.ifrmaeSwitch('iframe[src*=recognite]')
    cssBox = 'body > div.panel.window.messager-window > div.messager-body.panel-body.panel-body-noborder.window-body'

    if self.is_element_exist(cssBox):
        self.browerClick('body > div.panel.window.messager-window > div.panel-header.panel-header-noborder.window-header > div.panel-tool > a')
    self.ifrmaeSwitchDefault()




def ifrmaeSwitch(self, cssVal):
    '''此方法用于用于切换iframe,首先切回默认iframe然后切换到指定的iframe'''
    t1 = time.time()
    try:

        self.elementWait(cssVal)
        self.driver.switch_to.default_content()
        self.driver.switch_to.frame(self.driver.find_element_by_css_selector(cssVal))
        self.my_print_info("{0} Typed element: <{1}> content, Spend {2} seconds".format(success,
                                                                                        cssVal,
                                                                                        time.time() - t1))
    except Exception:
        self.my_print_error("{0} Unable to type element: <{1}> , Spend {2} seconds".format(fail,cssVal,
                                                                                                       time.time() - t1))
        raise


def ifrmaeSwitchDefault(self):
    '''此方法用于用于切换iframe, 恢复到默认'''
    t1 = time.time()
    try:
        self.driver.switch_to.default_content()
        time.sleep(1)
        self.my_print_info("{0}, Spend {1} seconds".format(success,time.time() - t1))
    except Exception:
        self.my_print_error("{0} Unable to type element, Spend {1} seconds".format(fail, time.time() - t1))
        raise



def getAutoZipCode(self):
    """自动生成邮编"""
    ZIP_CODE = random.randint(100000, 999999)
    # print ZIP_CODE
    return ZIP_CODE


def autoIDFZZJ(self):
    '''生成香港身份证号码'''
    list1 = [chr(i) for i in range(65, 91)]  # 大写字母+小写字母+数字
    list2 = [i for i in range(1, 27)]

    # print dict(zip(list1, list2))

    dict_idHM = {'A': 1, 'C': 3, 'B': 2, 'E': 5, 'D': 4, 'G': 7, 'F': 6, 'I': 9, 'H': 8, 'K': 11, 'J': 10, 'M': 13,
                 'L': 12, 'O': 15, 'N': 14, 'Q': 17, 'P': 16, 'S': 19, 'R': 18, 'U': 21, 'T': 20, 'W': 23, 'V': 22,
                 'Y': 25, 'X': 24, 'Z': 26}

    startFlag = list1[random.randrange(26)]
    # 开始的字母
    # print startFlag
    # 首字母对应的数值
    numSZM = int(dict_idHM[startFlag])
    # print numSZM
    # 中间字符串
    midVAl = self.autoTimeString(6)
    # print midVAl
    # 最后一位校验位
    verEnd = numSZM * 8
    for i in range(6):
        y = 7

        verEnd = verEnd + int(midVAl[i]) * y
        y = y - 1
        # print verEnd

    verEnd = verEnd % 11
    # print verEnd
    if verEnd == 10:
        verEnd = 'A'
    # print verEnd
    val = str(startFlag) + str(midVAl) + '(' + str(verEnd) + ')'
    return val



def getAutoSGZHM(self,area_code, age, gender='1'):
    """自动生成身份证ID需要四位参数 620524, 18, 1"""
    if str(area_code) not in list(area_dict.keys()):
        return None
    datestring = str(date(date.today().year - age, 1, 1) + timedelta(days=random.randint(0, 364))).replace("-",
                                                                                                           "")
    rd = random.randint(0, 999)
    if gender == 0:
        gender_num = rd if rd % 2 == 0 else rd + 1
    else:
        gender_num = rd if rd % 2 == 1 else rd - 1
    result = str(area_code) + datestring + str(gender_num).zfill(3)
    time.sleep(2)
    return result + str(
        check_code_list[sum([a * b for a, b in zip(id_code_list, [int(a) for a in result])]) % 11])

def getIDCard(self):
    zdLen = len(list(sorted(area_dict.keys())))
    rad = int(random.randrange(0, zdLen, 1))

    area_code = int(list(sorted(area_dict.keys()))[rad])

    day = (time.strftime("%d"))
    ageArg = 55 - int(day)

    print(ageArg)

    # area_code = (area_dict.keys()

    id_number = self.getAutoSGZHM(area_code, ageArg, 1)
    return id_number

def getAutoEmail(self):
    """自动生成电子邮箱"""
    Fist_email = "".join(random.sample(string.letters + string.digits, 9))
    last_email = '@163.com'
    EMAIL = '%s%s' % (Fist_email, last_email)
    # print EMAIL
    return EMAIL

def getRandString(self, leng):
    """此方法用于用于自动生成指定长度的字符串"""
    ran_str = ''.join(random.sample(string.ascii_letters, leng))
    return ran_str

def getRandNumber(self, leng):
    """此方法用于用于自动生成指定长度的数字"""

    ran_str = ''.join(random.sample(string.digits, leng))
    return ran_str



def getScreenshot(self,flag='error'):
    """
    截图,
    在这里我们把file_path这个参数写死,直接保存到我们项目根目录的一个文件夹.\Screenshots下
    """
    file_path = 'D:\\auto\\result\\image\\'
    # os.path.basename(__file__)[:-3] +
    rq = time.strftime('%Y%m%d%H%M', time.localtime(time.time()))
    screen_name = file_path + rq + flag+'.png'
    try:
        self.driver.get_screenshot_as_file(screen_name)

        logger.info("Had take screenshot and save to folder %s" %screen_name)
    except NameError as e:
        logger.error("Failed to take screenshot! %s" % e)
        self.getScreenshot()

# def getImage(self):
#     """
#     在这里我们把file_path这个参数写死,直接保存到我们项目根目录的一个文件夹.\Screenshots下
#     """
#     file_path = 'D:\\auto\\result\\image\\'
#     # os.path.basename(__file__)[:-3] +
#     rq = time.strftime('%Y%m%d%H%M', time.localtime(time.time()))
#     screen_name = file_path + rq + '.png'
#     try:
#         self.driver.get_screenshot_as_file(screen_name)
#
#         logger.info("Had take screenshot and save to folder %s" %screen_name)
#     except NameError as e:
#         logger.error("Failed to take screenshot! %s" % e)
#         self.getScreenshot()

def popInfo(self):
    root = tkinter.Tk()
    b = tkinter.Button(root, text="中登异常,请查看")
    b.pack()
    root.mainloop()

time.sleep(5)

def my_print_info(self, msg):
    logger.info(msg)


def my_print_error(self, msg):
    logger.error(msg)


def clearCache(self, flag='0'):
    '''此方法用于清除缓存和杀掉谷歌进程,输入flag标记,其中1表示清除'''
    if flag == '1':
        os.system('taskkill>nul 2>nul /im chrome.exe /f ')
        os.system('taskkill>nul 2>nul /im chromedriver.exe /f ')
    elif  flag == '0':
        pass
    else:
        pass


def elementWait(self, css, secs=10):
    """
    Waiting for an element to display.

    Usage:
    driver.element_wait("id=kw",10)
    """

    messages = 'Element: {0} not found in {1} seconds.'.format(css, secs)
    if css:
        WebDriverWait(self.driver, secs, 1).until(EC.presence_of_element_located((By.CSS_SELECTOR, css)), messages)
    else:
        raise NameError(
            "Please enter the correct targeting elements,'id','name','class','link_text','xpaht','css'.")




def getAge(self, birthday):
    '''根据生日,计算年龄'''
    t1 = time.time()
    self.my_print_info("{0} Start calculating age  : {1}, Spend {2} seconds".format(success, birthday, time.time() - t1))
    y = birthday[:4]
    m = birthday[4:6]
    d = birthday[6:]
    # get the current time in tuple format
    a = time.gmtime()
    # difference in day
    dd = a[2] - int(d)
    # difference in month
    dm = a[1] - int(m)
    # difference in year
    dy = a[0] - int(y)
    # checks if difference in day is negative
    if dd < 0:
        dd = dd + 30
        dm = dm - 1
        # checks if difference in month is negative when difference in day is also negative
        if dm < 0:
            dm = dm + 12
            dy = dy - 1
    # checks if difference in month is negative when difference in day is positive
    if dm < 0:
        dm = dm + 12
        dy = dy - 1

        self.my_print_info(self.my_print_info("{0} Your current age is {1}Years {2} Months & {3} Days Spend {4} seconds".format(success, dy,dm,dd, time.time() - t1)))


def is_not_visible(self, locator, timeout=720):
    '''此方法用于用于等待某个元素消失,默认超时120秒'''
    t1 = time.time()
    try:
        ui.WebDriverWait(self.driver, timeout).until_not(
            EC.visibility_of_element_located((By.CSS_SELECTOR, locator)))
        self.my_print_info("{0} Wait for the disappearance of the element: <{1}> content, Spend {2} seconds".format(success,
                                                                                                                    locator,
                                                                                                                    time.time() - t1))
        return True
    except TimeoutException:
        self.my_print_error("{0} Wait for the disappearance of the element: <{1}> , Spend {} seconds".format(fail,
                                                                                          locator,
                                                                                          time.time() - t1))
        return False

def is_visible(self, locator, timeout=120):
    ''''此方法用于用于等待某个元素可见,默认超时120秒'''
    t1 = time.time()
    try:
        ui.WebDriverWait(self.driver, timeout).until(
            EC.visibility_of_element_located((By.CSS_SELECTOR, locator)))
        self.my_print_info("{0} Wait for the appearance of the element : <{1}> content, Spend {2} seconds".format(success,
                                                                                        locator,
                                                                                        time.time() - t1))
        return True
    except TimeoutException:
        self.my_print_error("{0} Wait for the appearance of the element : <{1}> , Spend {} seconds".format(fail,
                                                                                          locator,
                                                                                          time.time() - t1))
        return False

# def isMustBack(self, css):
#     '''#判断银行是否必填和是否显示,如果包含validatebox-must则为1'''
#     val = self.driver.find_element_by_css_selector(css).get_attribute('class')
#     if "validatebox-must" in val:
#         return '1'
#         print u'该元素为必填项'
#     else:
#         return '0'
#         print u'该元素为非必填项'
#
# def isDisableBack(self, css):
#     '''#判断银行是否置灰,如果包含validatebox-disabled则为1'''
#     val = self.driver.find_element_by_css_selector(css).get_attribute('class')
#     if "validatebox-disabled" in val:
#         return '1'
#         print u'该元素不可显示'
#     else:
#         return '0'
#         print u'该元素可显示'
#
def isMustBack(self, css):
    '''#判断银行是否必填和是否显示,如果包含validatebox-must则为1'''
    val = self.driver.find_element_by_css_selector(css).get_attribute('class')
    if "must" in val:
        return '1'
        print('该元素为必填项')
    else:
        return '0'
        print('该元素为非必填项')

def isDisableBack(self, css):
    '''#判断银行是否置灰,如果包含validatebox-disabled则为1'''
    val = self.driver.find_element_by_css_selector(css).get_attribute('class')
    if "disable" in val:
        return '1'
        print('该元素不可显示')
    else:
        return '0'
        print('该元素可显示')

def is_element_exist(self, css):
    """此方法用于用于判断元素是否存在"""
    flag = True
    t1 = time.time()

    try:
        self.driver.find_element_by_css_selector(css)
        self.my_print_info(
            "{0} element exists  : <{1}> content, Spend {2} seconds".format(success,css,time.time() - t1))
        return flag

    except:
        return False
        raise

def getTitle(self, cssval):
    """此方法用于用于判断元素的title是否为空"""
    flag = True
    t1 = time.time()
    time.sleep(1)

    try:
        vTitle = self.driver.find_element_by_css_selector(cssval).get_attribute("title")
        self.my_print_info(
            "{0} element exists  : <{1}> content, Spend {2} seconds".format(success, vTitle, time.time() - t1))
        return vTitle
    finally:
        pass

def getAttribute(self, cssVal, cssvAttr):
    """此方法用于用于判断元素的title是否为空"""
    flag = True
    t1 = time.time()

    try:
        val = self.driver.find_element_by_css_selector(cssVal).get_attribute(cssvAttr)
        self.my_print_info(
            "{0} element exists  : <{1}> content, Spend {2} seconds".format(success, val, time.time() - t1))
        return val
    finally:
        pass

def is_title_null(self, css):
    """此方法用于用于判断元素的title是否为空"""
    flag = True
    t1 = time.time()

    try:
        vflag = self.driver.find_element_by_css_selector(css).get_attribute("title")
        if vflag.strip() == "":
            self.my_print_info(
                "{0} Whether title is empty  : <{1}> Spend {2} seconds".format(success, css, time.time() - t1))
            return True
        elif vflag.strip():
            self.my_print_info(
                "{0} Whether title is empty  : <{1}> Spend {2} seconds".format(fail, css, time.time() - t1))
            return False
        else:
            pass
    finally:
        pass

def is_title_exit(self, css):
    """此方法用于用于判断元素的title是否为空"""
    flag = True
    t1 = time.time()

    try:
        vflag = self.driver.find_element_by_css_selector(css).get_attribute("title")
        if vflag != '':
            self.my_print_info(
                "{0} Whether title is exit  : <{1}> Spend {2} seconds".format(success, css, time.time() - t1))
            return True
        else:
            self.my_print_info(
                "{0} Whether title is exit  : <{1}> Spend {2} seconds".format(fail, css, time.time() - t1))
            return False
    finally:
        pass

def getAutoZipCode(self):
    """自动生成邮编"""
    ZIP_CODE = random.randint(100000, 999999)
    # print ZIP_CODE
    return ZIP_CODE

def check_zuzhi(self,zuzhi_str):
    '''组织机构代码'''
    zuzhi_str = str(zuzhi_str)
    zuzhi_str = zuzhi_str.upper().replace('-', '')
    search = re.search(r'^[\dA-Z]{8}[X\d]$', zuzhi_str, re.S)
    if search:
        verify_code = [3, 7, 9, 10, 5, 8, 4, 2]
        verify_code = 11 - sum([int(
            (ord(zuzhi_str[index]) - 55) if zuzhi_str[index].isalpha() else zuzhi_str[index]
        ) * verify_code[index] for index in range(8)]) % 11
        verify_code = 'X' if verify_code == 10 else ('0' if verify_code == 11 else str(verify_code))
        return zuzhi_str if verify_code == zuzhi_str[-1] else False
    return False

def check_xinyong(self,xinyong_str):
    '''统一社会信用代码证'''
    xinyong_str = str(xinyong_str)
    xinyong_str = xinyong_str.upper()
    if len(xinyong_str) != 18:
        return False
    search = re.search(r'^(1[129]|5[1239]|9[123]|Y1)\d{6}[\dA-Z]{8}[X\d][\dA-Z]$', xinyong_str, re.S)
    if search:
        if self.check_zuzhi(xinyong_str[8:17]):
            str_to_num = {
                'A': 10, 'B': 11, 'C': 12, 'D': 13, 'E': 14, 'F': 15, 'G': 16, 'H': 17, 'J': 18, 'K': 19,
                'L': 20, 'M': 21, 'N': 22, 'P': 23, 'Q': 24, 'R': 25, 'T': 26, 'U': 27, 'W': 28, 'X': 29, 'Y': 30}
            num_to_str = {
                10: 'A', 11: 'B', 12: 'C', 13: 'D', 14: 'E', 15: 'F', 16: 'G', 17: 'H', 18: 'J', 19: 'K',
                20: 'L', 21: 'M', 22: 'N', 23: 'P', 24: 'Q', 25: 'R', 26: 'T', 27: 'U', 28: 'W', 29: 'X', 30: 'Y'}
            verify_code = [1, 3, 9, 27, 19, 26, 16, 17, 20, 29, 25, 13, 8, 24, 10, 30, 28]
            verify_code = 31 - sum([(
                                        str_to_num.get(xinyong_str[index], 0) if xinyong_str[
                                            index].isalpha() else int(
                                            xinyong_str[index])
                                    ) * verify_code[index] for index in range(17)]) % 31
            verify_code = num_to_str.get(verify_code, '') if verify_code > 9 else verify_code
            return xinyong_str if verify_code == xinyong_str[-1] else False
    return False

CODEMAP = string.digits + string.ascii_uppercase  # 用数字与大写字母拼接成CODEMAP,每个字符的index就是代表该字符的值
WMap = [3, 7, 9, 10, 5, 8, 4, 2]  # 加权因子列表


def getOrgCode(self):
    ww = [3, 7, 9, 10, 5, 8, 4, 2]  # suan fa yin zi
    cc = []
    dd = 0

    for i in range(8):  # gei CC fu zhi
        cc.append(random.randint(1, 9))
        dd = dd + cc[i] * ww[i]
    for i in range(len(cc)):
        cc[i] = str(cc[i])
    C9 = 11 - dd % 11
    if C9 == 10:
        C9 = 'X'
    else:
        if C9 == 11:
            C9 = '0'
        else:
            C9 = str(C9)
    cc.append('-' + C9)

    return "".join(cc)

def getOrgJY(self):
    rad = random.randrange(len(orgList))

    code= orgList[rad]

    return code



def createOrgNumber(self):
    prelist = ["130", "131", "132", "133", "134", "135", "136", "137", "138", "139", "147", "150", "151", "152", "153",
               "155", "156", "157", "158", "159", "186", "187"]
    return random.choice(prelist) + "".join(time.strftime('%Y%M%d%H%M%S', time.localtime(time.time())))

def UnCreditCode(self):
    code = CreditIdentifier()
    zdLen = len(list(sorted(area_dict.keys())))
    rad = int(random.randrange(0, zdLen, 1))
    area_code = int(list(sorted(area_dict.keys()))[rad])
    day = (time.strftime("%d"))
    ageArg = 55 - int(day)
    zzjgdm = self.getOrgJY()  #带有校验
    para = '91' + self.getIDCard()[:6] + zzjgdm[:8] + zzjgdm[-1:] + self.getRandNumber(1)
    self.my_print_info(zzjgdm)

    # cerCode = code.getSocialCreditCode(para)
    cerCode = para
    self.my_print_info(cerCode)
    return cerCode



def getAutoEmail(self):
    """自动生成电子邮箱"""
    Fist_email = "".join(random.sample(string.letters + string.digits, 9))
    last_email = '@163.com'
    EMAIL = '%s%s' % (Fist_email, last_email)
    # print EMAIL
    return EMAIL

def getRandString(self, leng):
    """此方法用于用于自动生成指定长度的字符串"""
    ran_str = ''.join(random.sample(string.ascii_letters, leng))
    return ran_str

def getRandNumber(self, leng):
    """此方法用于用于自动生成指定长度的数字"""

    ran_str = ''.join(random.sample(string.digits, leng))
    return ran_str

def getName(self, k):
    """此方法用于用于自动生成用户名,不需要输入开户名称"""

    rad = random.randrange(0, 101, 2)
    userCode = self.getShanGuo() + self.getIdInfo(k) + str(rad)
    return userCode

def continueOperate(sefl):
    """此方法用于中断操作"""
    raw_input_A = input("raw_input: \n")
    print(input())

def acceptAlert(self):
    """
    Accept warning box.

    Usage:
    driver.accept_alert()
    """
    t1 = time.time()
    self.driver.switch_to.alert.accept()
    self.my_print_info("{0} Accept warning box, Spend {1} seconds".format(success, time.time() - t1))

def dismissAlert(self):
    """
    Dismisses the alert available.

    Usage:
    driver.dismiss_alert()
    """
    t1 = time.time()
    self.driver.switch_to.alert.dismiss()
    self.my_print_info("{0} Dismisses the alert available, Spend {1} seconds".format(success, time.time() - t1))

def inputDouble(self, css, val):
    """此方法用于双重输入"""

    t1 = time.time()

    try:
        self.elementWait(css)
        self.driver.find_element_by_css_selector(css).send_keys(val)
        self.driver.find_element_by_css_selector(css).send_keys(Keys.ENTER)
        # self.browerInput(css,val)
        # self.clickEnter(css)

        time.sleep(2)
        self.driver.find_element_by_css_selector(
            "div.panel.window.messager-window.password-window > div > div > input").send_keys(val)
        # self.browerInput("div.panel.window.messager-window.password-window > div > div > input",val)
        button = self.driver.find_element_by_css_selector(
            "div.panel.window.messager-window.password-window > div > div.messager-button > div > a > span")
        self.driver.execute_script('$(arguments[0]).click()', button)
        self.my_print_info("{0} Two confirmation input: <{1}> , Spend {2} seconds".format(success,
                                                                                        css,
                                                                                        time.time() - t1))
    except Exception:
        self.my_print_error("{0} Two confirmation input: <{1}> , Spend {2} seconds".format(fail,
                                                                                                 css,
                                                                                                 time.time() - t1))
        raise

def executeJSClick(self, cssVal):
    '''执行js按钮,传入css值'''
    t1 = time.time()

    try:
        self.elementWait(cssVal)

        button2 = self.driver.find_element_by_css_selector(cssVal)
        time.sleep(1)
        self.driver.execute_script('$(arguments[0]).click()', button2)
        self.my_print_info("{0} execute js: <{1}> , Spend {2} seconds".format(success,
                                                                                        cssVal,
                                                                                        time.time() - t1))
    except Exception:
        self.my_print_error("{0} execute js: <{1}> , Spend {2} seconds".format(fail,
                                                                                                 cssVal,
                                                                                                 time.time() - t1))
        raise



def inputListComma(self, cssVal, listVal):
    '''传入字符串,以逗号分割切成,不能有空格,否则报错'''
    t1 = time.time()

    try:
        self.elementWait(cssVal)
        listVales = listVal.split(',')
        time.sleep(1)
        rad = random.randrange(len(listVales))
        self.driver.find_element_by_css_selector(cssVal).send_keys(listVales[rad])
        time.sleep(1)
        self.driver.find_element_by_css_selector(cssVal).send_keys(Keys.ENTER)
        self.my_print_info("{0} List input : <{1}> , Spend {2} seconds".format(success,
                                                                                        cssVal,
                                                                                        time.time() - t1))
    except Exception:
        self.my_print_error("{0} List input : <{1}> , Spend {2} seconds".format(fail,
                                                                                                 cssVal,
                                                                                                 time.time() - t1))
        raise

def getListVal(self, listVal):
    '''传入字符串,以逗号分割切成,不能有空格,否则报错'''
    t1 = time.time()

    try:

        listVales = listVal
        time.sleep(1)
        rad = random.randrange(len(listVales))
        return listVales[rad]
        self.my_print_info("{0} List return , Spend {1} seconds".format(success,
                                                                                        time.time() - t1))
    except Exception:
        self.my_print_error("{0} List return  Spend {1} seconds".format(fail,
                                                                                                 time.time() - t1))
        raise


def clickWinPopBox(self):
    '''此方法用于点击弹出的Win的弹出框'''
    cssQR = 'body > div.panel.window.messager-window > div.messager-body.panel-body.panel-body-noborder.window-body > div.messager-button > div > a > span'
    time.sleep(1)
    # 点击弹出框确认按钮
    self.browerClick(cssQR)

def createRadomForString(self):
    '''随机生成一个1-10之间随机数并强制转换了字符串形式'''
    return  str(random.randrange(0, 10, 1))

def createPhone(self):

    '''随机生成手机号码'''

    prelist = ["130", "131", "132", "133", "134", "135", "136", "137", "138", "139", "147", "150", "151", "152",
               "153",
               "155", "156", "157", "158", "159", "186", "187"]
    return random.choice(prelist) + "".join(random.choice("0123456789") for i in range(8))

def autoPhone13(self):
    '''随机生成手机号码, 并以13开头'''

    prelist = ["130", "131", "132", "133", "134", "135", "136", "137", "138", "139"]
    return random.choice(prelist) + "".join(random.choice("0123456789") for i in range(8))

def autoPhone15(self):
    '''随机生成手机号码, 并以15开头'''

    prelist = ["150", "151", "152", "153", "155", "156", "157", "158", "159"]
    return random.choice(prelist) + "".join(random.choice("0123456789") for i in range(8))

def autoPhone18(self):
    '''随机生成手机号码, 并以18开头'''


    prelist = ["186", "187"]
    return random.choice(prelist) + "".join(random.choice("0123456789") for i in range(8))

def autoTimeString(self,len):
    '''生成当前日期的时间串,并截取参数对应长度后返回,时、分、秒,月,日,年,目前长14'''

    v =time.strftime('%H%M%S%m%d%Y', time.localtime(time.time()))
    s = v[0:len]
    return s



def getMobInputYZM(self, hj,cusCode, cssAN, cssYZM):
    '''通过方法来获取手机号码,依次输入环境fat或uat电话号码css,点击按钮css,验证码css'''

    try:

        # 电话

        self.driver.find_element_by_css_selector(cssAN).click()
        time.sleep(2)
        # cssFlag = 'body > div.panel.window.messager-window > div.panel-header.panel-header-noborder.window-header > div.panel-title'
        cssFlag = 'body > div > div.panel-header.panel-header-noborder.window-header > div.panel-title'
        self.is_visible(cssFlag)

        cssWind1 = "body > div.panel.window.messager-window > div.messager-body.panel-body.panel-body-noborder.window-body > div.messager-button > div > a"
        cssWind2 = "body > div.panel.window.messager-window > div.messager-body.panel-body.panel-body-noborder.window-body > div.messager-button > div > a > span"

        if self.is_element_exist(cssWind1):
            self.executeJSClick(cssWind1)
        elif self.is_element_exist(cssWind2):
            self.executeJSClick(cssWind2)
        else:
            pass


        import cx_Oracle
        if hj == 'fat':
            db = cx_Oracle.connect(globaVar.dbfat)
        elif hj == 'uat':
            db = cx_Oracle.connect(globaVar.dbuat)
        time.sleep(1)
        cursor = db.cursor()
        sql = "select * from (select sms_code from opp_busi_sms where cust_code = \'%s\' order by oper_time desc) where rownum=1" % cusCode
        print(sql)
        time.sleep(1)
        rs = cursor.execute(sql)
        li = rs.fetchall()
        time.sleep(1)
        mli = str(li)[3:9]
        print(mli)
        db.close()
        time.sleep(1)
    finally:
        self.driver.find_element_by_css_selector(cssYZM).send_keys(mli)
        time.sleep(1)

def clickNext(self):
    '''下一步next,然后等待了1秒'''

    t1 = time.time()
    try:

        flag = self.driver.page_source
        buttenNext = self.driver.find_element_by_css_selector("#next")
        self.driver.execute_script('$(arguments[0]).click()', buttenNext)
        time.sleep(1)
        flag2 = self.driver.page_source
        if flag != flag2:
            self.my_print_info("{0} page source changed, Spend {1} seconds".format(success,time.time() - t1))
        else:
            self.my_print_info("{0} page source changed, Spend {1} seconds".format(fail, time.time() - t1))
    except Exception:

        raise
    finally:
        self.is_not_visible("body > div.panel.window.messager-window.message-loading > div")




def submit(self):

    '''提交submit,其中等待了3秒'''

    time.sleep(1)
    self.is_visible("#submit")
    self.driver.find_element_by_css_selector("#submit").click()
    time.sleep(1)

    self.driver.switch_to.default_content()
    cssqjcg = 'body > div.panel.window.messager-window > div.messager-body.panel-body.panel-body-noborder.window-body > div.messager-button > div > a.l-btn'
    self.executeJSClick(cssqjcg)

def getNumberSart(self, start):
    '''输入开始字符后拼接时分秒'''
    v = start + time.strftime('%H%M%S', time.localtime(time.time()))
    return v

# 判断银行是否必填和是否显示
#######################################################################

def inputBack(self, cssDH, backDH):
    '''输入银行卡代号'''
    self.driver.find_element_by_css_selector(cssDH).send_keys(backDH)
    time.sleep(1)
    self.driver.find_element_by_css_selector(cssDH).send_keys(Keys.ENTER)

def inpuBackSCSR(self, cssKH, backVal):
    ''''#输入银行确认框,参数css,值'''
    time.sleep(1)

    self.inputDouble(cssKH, backVal)

    time.sleep(1)

def isMustBack(self, css):
    '''#判断银行是否必填和是否显示,如果包含validatebox-must则为1'''
    val = self.driver.find_element_by_css_selector(css).get_attribute('class')
    if "validatebox-must" in val:
        return '1'
        print('该元素为必填项')
    else:
        return '0'
        print('该元素为非必填项')

def isDisableBack(self, css):
    '''#判断银行是否置灰,如果包含validatebox-disabled则为1'''
    val = self.driver.find_element_by_css_selector(css).get_attribute('class')
    if "validatebox-disabled" in val:
        return '1'
        print('该元素不可显示')
    else:
        return '0'
        print('该元素可显示')

def inputDoubCert(self,valcs):
    '''主要用于判断双人见证开户'''

    self.browerClear('#D_WITNESS +  span > input[type=text]')
    self.inputListComma('#D_WITNESS +  span > input[type=text]',valcs)


def inputOrgNumber(self,number):
    '''跨机构时,选择下拉的'''
    cssOrg = '#ORG_CODE + span > input'
    self.elementWait(cssOrg)
    self.browerClear(cssOrg)
    self.browerInput(cssOrg,number)
    time.sleep(1)
    self.clickEnter(cssOrg)

def inputRiskAss2(self, listVal):
    '''风险测评,输入列表字符串,后台方法自动处理'''
    time.sleep(3)

    ls = list(listVal)
    size = len(listVal)

    for i in range(size):
        indexa = i + 1
        indexb = int(ls[i])

        var = "#flowPanel > div.flow-busi-wrap.clearfix > div.flow-work-wrap.clearfix > div.risk-node.hide > div " \
              "> div.risk-content-wrap > div.input-wrap.clearfix > div.fast-input-item > input[colnum=\'%d\']" % (indexa)
        # self.my_print_error(var)
        # self.driver.find_element_by_css_selector(var).send_keys(listVal[i])
        self.browerInput(var,listVal[i])


    # 下一步
    buttenNext = self.driver.find_element_by_css_selector("#next")
    cssQS = 'body > div.panel.window.messager-window > div.panel-header.panel-header-noborder.window-header > div.panel-title'
    self.driver.execute_script('$(arguments[0]).click()', buttenNext)
    time.sleep(2)

    # 测评结果下一步,在弹出框
    self.driver.find_element_by_css_selector("#next > span").click()
    self.is_not_visible("body > div.panel.window.messager-window.message-loading > div")
    time.sleep(2)

# def inputRiskAss2(self, listVal):
#     '''风险测评,输入列表字符串,后台方法自动处理'''
#     time.sleep(3)
#
#     ls = list(listVal)
#     size = len(listVal)
#
#     for i in range(size):
#         indexa = i + 2
#         indexb = int(ls[i])
#         time.sleep(0.5)
#         var = "#flowPanel > div.flow-busi-wrap.clearfix > div.flow-work-wrap.clearfix > " \
#               "div.risk-node.hide > div > div.risk-content-wrap > div.risk-col-wrap > div:nth-child(%d) > " \
#               "div.obviousbox.clearfix > div > label:nth-child(%d) > span" % (indexa, indexb)
#         self.my_print_error(var)
#
#         time.sleep(0.5)
#         self.driver.find_element_by_css_selector(var).click()
#         time.sleep(1)
#
#     # 下一步
#     buttenNext = self.driver.find_element_by_css_selector("#next")
#     cssQS = 'body > div.panel.window.messager-window > div.panel-header.panel-header-noborder.window-header > div.panel-title'
#     if self.is_element_exist(cssQS):
#         for i in range(size):
#             indexa = i + 2
#             indexb = int(ls[i])
#             time.sleep(0.5)
#             var = "#flowPanel > div.flow-busi-wrap.clearfix > div.flow-work-wrap.clearfix > " \
#                   "div.risk-node.hide > div > div.risk-content-wrap > div.risk-col-wrap > div:nth-child(%d) > " \
#                   "div.obviousbox.clearfix > div > label:nth-child(%d) > span" % (indexa, indexb)
#             self.my_print_error(var)
#
#             time.sleep(0.5)
#             self.driver.find_element_by_css_selector(var).click()
#             time.sleep(1)
#     self.driver.execute_script('$(arguments[0]).click()', buttenNext)
#     time.sleep(2)
#
#     # 测评结果下一步,在弹出框
#     self.driver.find_element_by_css_selector("#next > span").click()

def logout(self):
    '''登出,目前只判断了二类登出的情况'''
    self.driver.switch_to.default_content()
    self.driver.find_element_by_css_selector("div.user-info-box.pull-right  a.icon-logout").click()

    cssAN2 = 'body > div.panel.window.messager-window > div.messager-body.panel-body.panel-body-noborder.window-body > div.messager-button > div:nth-child(1) > a'
    if self.is_element_exist(cssAN2):
        self.executeJSClick(cssAN2)
    else:

        for i in range(8,20):
            cssAN1 = 'body > div:nth-child(%d) > div.messager-body.panel-body.panel-body-noborder.window-body > div.messager-button > div:nth-child(1) > a'%i
            if self.is_element_exist(cssAN1):
                self.executeJSClick(cssAN1)
                return True
            else:
                pass


def close(self):
    '''关闭浏览器,且无其它任何操作'''
    self.driver.close()

def autoOrgCode(self):
    '''生产组织机构代码证'''
    ww = [3, 7, 9, 10, 5, 8, 4, 2]  # suan fa yin zi
    cc = []
    dd = 0

    for i in range(8):  # gei CC fu zhi
        cc.append(random.randint(1, 9))
        dd = dd + cc[i] * ww[i]
    for i in range(len(cc)):
        cc[i] = str(cc[i])
    C9 = 11 - dd % 11
    if C9 == 10:
        C9 = 'X'
    else:
        if C9 == 11:
            C9 = '0'
        else:
            C9 = str(C9)
    cc.append('-' + C9)
    return "".join(cc)

def auditOnelogin(self, url):
    ''' 一审操作页面登,需要输入环境fat或uat'''

    if url == "fat" and globaVar.um == '0':
        self.gylogin('10036', '123321', globaVar.url)
    elif url == "fat" and globaVar.um == '1':
        self.umlogin('LIUCHENG867', 'LIUCHENG867', globaVar.url)


    else:
        # uat审核
        url = 'http://10.25.168.170:30073/opp_webapp/'
        umname = 'ITBANLI528'
        umpass = '123321'
        self.umlogin(umname, umpass, url)

def auditTwologin(self, url):
    ''' 二审操作页面登,需要输入环境fat或uat'''

    if url == "fat" and globaVar.um == '0':
        self.gylogin('10036', '123321', globaVar.url)
    elif url == "fat" and globaVar.um == '1':
        self.umlogin('LIUCHENG867', 'LIUCHENG867', globaVar.url)


    else:
        # uat审核
        url = 'http://10.25.168.170:30073/opp_webapp/'
        umname = 'ITFUHE868'
        umpass = '123321'
        self.umlogin(umname, umpass, url)

def getBusiNo(self, hj, key, val):

    '''key,,val 来获取业务单号进行业务审核'''

    # 查询返回对等审核的usercode

    import cx_Oracle

    if hj == 'fat':
        db = cx_Oracle.connect(globaDB.dbfat)
    elif hj == 'uat':
        db = cx_Oracle.connect(globaDB.dbuat)
    elif hj == 'loc':
        db = cx_Oracle.connect(globaDB.dbloc)

    cursor = db.cursor()

    # sql = "select cust_code from opp_busi_data where id_code = \'%s\'  and id_type = \'%s\'" % (cardid, idtype)
    sql = "select * from (select b_sno from opp_busi_data where id_type =\'%s\' and  id_code = \'%s\' order by oper_time desc ) where rownum = 1" % (
    key, val)
    # print sql
    time.sleep(1)
    rs = cursor.execute(sql)
    li = rs.fetchall()
    code = str(li)
    db.close()
    #打印业务单号,此处引用正则来过滤到数字,去掉其它字符
    code = sub("\D", "", code)
    self.my_print_info(code)
    time.sleep(3)
    return code



def accountReview(self, k, v):
    '''开户审核,需要输入Key和val证件类型所对应的证件号码,其中通过后台参数来判断环境'''
    if globaVar.event == 'fat':
        shuser = 'LIUCHENG867'
        shpwd = 'LIUCHENG867'
        shuser2 = 'LIUCHENG867'
        shpwd2 = 'LIUCHENG867'
    elif globaVar.event == 'uat':
        shuser = 'ITBANLI528'
        shpwd = '123321'
        shuser2 = 'ITFUHE868'
        shpwd2 = '123321'

    print(self.getUserCode(globaVar.event, k, v))
    # 登录审核页面#######
    self.loginNoRUL(shuser, shpwd)
    custCode = self.getUserCode(globaVar.event, k, v)
    # 调用输入客户代码
    self.inputBusName(custCode)
    # 一次审核
    self.auth()
    self.logout()
    # 调用输入客户代码,二次审核
    self.loginNoRUL(shuser2, shpwd2)
    self.inputBusName(custCode)
    self.auth()

def getBusiNoByuserCode(self, hj, useCode, busiCode):

    '''通过useCode,busiCode 来获取业务单号进行业务审核'''

    # 查询返回对等审核的usercode

    import cx_Oracle

    if hj == 'fat':
        db = cx_Oracle.connect(globaDB.dbfat)
    elif hj == 'uat':
        db = cx_Oracle.connect(globaDB.dbuat)
    elif hj == 'loc':
        db = cx_Oracle.connect(globaDB.dbloc)

    cursor = db.cursor()

    # sql = "select cust_code from opp_busi_data where id_code = \'%s\'  and id_type = \'%s\'" % (cardid, idtype)
    sql = "select * from (select b_sno from opp_busi_data where cust_code =\'%s\' and busi_code =\'%s\' order by oper_time desc ) where rownum = 1" % (
        useCode, busiCode)
    print(sql)
    time.sleep(1)
    rs = cursor.execute(sql)
    li = rs.fetchall()
    code = str(li)
    db.close()
    #打印业务单号,此处引用正则来过滤到数字,去掉其它字符
    code = sub("\D", "", code)
    self.my_print_info(code)
    time.sleep(1)
    return code

def accountReview2(self, k, v):
    '''开户审核,需要输入Key和val证件类型所对应的证件号码,其中通过后台参数来判断环境,需要关闭浏览器'''

    if globaVar.event == 'fat':
        shuser = 'LIUCHENG867'
        shpwd = 'LIUCHENG867'
        shuser2 = 'LIUCHENG867'
        shpwd2 = 'LIUCHENG867'
        url = globaVar.faturl
    elif globaVar.event == 'uat':
        shuser = 'ITBANLI528'
        shpwd = '123321'
        shuser2 = 'ITFUHE868'
        shpwd2 = '123321'
        url = globaVar.uaturl

    print(self.getBusiNo(globaVar.event, k, v))
    # 登录审核页面#######
    self.umlogin(shuser, shpwd,url)
    busiNo = self.getBusiNo(globaVar.event, k, v)
    self.my_print_info('autoNo- %s' % busiNo)
    # 调用输入客户代码
    self.inputBusNo(busiNo)
    # 一次审核
    self.auth()
    time.sleep(1)
    if globaVar.event == 'uat':
        self.close()
    if globaVar.event == 'fat':
        '''如果是FAT则二审,否则就一审'''
        #二次审核,此处不再二次输入
        self.inputBusNo(busiNo)
        self.auth()
        time.sleep(1)

def accountReviewByuseCode(self, useCode, busiCode, count ):
    '''开户审核,需要输入Key和val证件类型所对应的证件号码,其中通过后台参数来判断环境,需要关闭浏览器'''

    if globaVar.event == 'fat':
        shuser = 'LIUCHENG867'
        shpwd = 'LIUCHENG867'
        shuser2 = 'LIUCHENG867'
        shpwd2 = 'LIUCHENG867'
        url = globaVar.faturl
    elif globaVar.event == 'uat':
        shuser = 'ITBANLI528'
        shpwd = '123321'
        shuser2 = 'ITFUHE868'
        shpwd2 = '123321'
        url = globaVar.uaturl

    print(self.getBusiNoByuserCode(globaVar.event, useCode, busiCode))
    # 登录审核页面#######
    self.umlogin(shuser, shpwd,url)
    busiNo = self.getBusiNoByuserCode(globaVar.event,useCode, busiCode)
    self.my_print_info('autoNo- %s' % busiNo)


    # 调用输入客户代码
    if count == '1':
        self.inputBusNo(busiNo)
        self.authByuseCode()
    elif count == '2':
        self.inputBusNo(busiNo)
        self.authByuseCode()
        self.inputBusNo(busiNo)
        self.authByuseCode()
    elif count == '3':
        self.inputBusNo(busiNo)
        self.authByuseCode()
        self.inputBusNo(busiNo)
        self.authByuseCode()
        self.inputBusNo(busiNo)
        self.authByuseCode()


def enterMenu(self, menu):
    '''管理员业务中进入数字菜单,需要输入菜单序列号'''

    self.ifrmaeSwitch('iframe[src*=FIN]')

    # 进入菜单
    cssInput = 'body > div.biz-nav-new.clearfix > div.menu-search-wrap > div.menu-search-box > input'
    cssSelect = 'body > div.biz-nav-new.clearfix > div.menu-search-wrap > div.menu-search-box > div > ul > li[data-menu-name="%s"]'%(menu)
    self.driver.find_element_by_css_selector(cssInput).send_keys(menu)
    time.sleep(1)
    self.my_print_info(cssSelect)
    #选择对应的菜单

    self.browerClick(cssSelect)

    self.is_not_visible("body > div.panel.window.messager-window.message-loading > div > div")

    self.ifrmaeSwitchDefault()

    self.ifrmaeSwitch('iframe[src*=operator]')


def inputBusName(self, vuserCode):
    '''审核页面输入客户代码,清空开始日志输入当前日志后点击搜索,可能要废'''

    time.sleep(2)

    self.ifrmaeSwitch('iframe[src*=genericParam]')
    # 开始日期
    cssKSRQ = "body > div.panel.datagrid > div > div.datagrid-queryForm > form > div > div:nth-child(5) > span.combo.datebox > input"
    time.sleep(1)

    # cssKHDM = 'body > div.panel.datagrid > div > div.datagrid-queryForm > form > div > div:nth-child(4) > input'
    #暂时修改为业务单号来进行
    cssKHDM = 'body > div.panel.datagrid > div.datagrid-wrap > div > form > div > div:nth-child(1) > input'


    # 右边的查询按钮
    cssCQAN = 'body > div.panel.datagrid > div > div.datagrid-queryForm > form > div > div:nth-child(7) > div > a > span.btn-text'
    time.sleep(1)

    self.driver.find_element_by_css_selector(cssKSRQ).clear()
    time.sleep(1)
    self.driver.find_element_by_css_selector(cssKSRQ).send_keys(time.strftime("%Y%m%d"))
    time.sleep(1)
    self.driver.find_element_by_css_selector(cssKHDM).clear()
    self.driver.find_element_by_css_selector(cssKHDM).send_keys(vuserCode)
    time.sleep(1)
    self.driver.find_element_by_css_selector(cssCQAN).click()

def inputBusNo(self, busiNo):
    '''审核页面输入客户代码,清空开始日志输入当前日志后点击搜索'''

    time.sleep(1)
    self.ifrmaeSwitchDefault()
    self.ifrmaeSwitch('iframe[src*=genericParam]')
    # 开始日期
    cssKSRQ = "body > div.panel.datagrid > div > div.datagrid-queryForm > form > div > div:nth-child(5) > span.combo.datebox > input"
    time.sleep(1)

    # cssKHDM = 'body > div.panel.datagrid > div > div.datagrid-queryForm > form > div > div:nth-child(4) > input'
    # 暂时修改为业务单号来进行
    cssYWDH1 = 'body > div.panel.datagrid > div.datagrid-wrap > div.datagrid-queryForm > form > div > div:nth-child(1) > input'
    cssYWDH2 = 'body > div.panel.datagrid > div.datagrid-wrap.panel-body.panel-body-noborder > div.datagrid-queryForm > form > div > div:nth-child(1) > input'
    # 右边的查询按钮
    cssCQAN = 'body > div.panel.datagrid > div > div.datagrid-queryForm > form > div > div:nth-child(7) > div > a > span.btn-text'
    time.sleep(1)
    #暂时注释掉输入日期
    # self.driver.find_element_by_css_selector(cssKSRQ).clear()
    # time.sleep(1)
    # self.driver.find_element_by_css_selector(cssKSRQ).send_keys(time.strftime("%Y%m%d"))
    # time.sleep(1)

    print(self.getTitle('body > div.panel.datagrid > div.datagrid-wrap.panel-body.panel-body-noborder > div.datagrid-queryForm > form > div > div:nth-child(1) > span'))

    self.driver.find_element_by_css_selector(cssYWDH2).clear()
    self.driver.find_element_by_css_selector(cssYWDH2).send_keys(busiNo)
    time.sleep(1)
    self.driver.find_element_by_css_selector(cssCQAN).click()


def auth(self):

    time.sleep(3)
    # 选择一列
    cssClick = '#datagrid-row-r1-2-0 > td:nth-child(3)'

    # 生成资金账号
    cssSC1 = '#bizInfo > div > fieldset.kui-fieldset.account-info-wrap.fieldset > div.info-wrap > div:nth-child(2) > span.desc-val.desc-full-width > span > span'
    cssSC2 = '#bizInfo > div > fieldset.kui-fieldset.account-info-wrap.fieldset > div.info-wrap > div:nth-child(1) > span.desc-val.desc-full-width > span > span'

    # 点击第一列
    self.driver.find_element_by_css_selector(cssClick).click()

    time.sleep(3)
    # 确认按钮
    cssQRAN = "body > div.panel.window.messager-window > div.messager-body > div > div:nth-child(1) > a"



    # 获取是否有资金账号,此处选切回默认然后再到切一次

    self.driver.switch_to.default_content()
    self.driver.switch_to.frame(self.driver.find_element_by_css_selector('div.panel > div> iframe:nth-child(1)'))
    time.sleep(1)
    cjzhText = self.driver.find_element_by_css_selector('#CUACCT_CODE').get_attribute("title")
    print(cjzhText)

    cjzhDis = self.driver.find_element_by_css_selector('#CUACCT_CODE').get_attribute("disabled")

    if cjzhText.strip() == '':
        print('one')
        #此处用于处理多种情况下的点击资金按钮
        if self.is_element_exist(cssSC1):
            self.driver.find_element_by_css_selector(cssSC1).click()
            time.sleep(1)
        elif self.is_element_exist(cssSC2):
            self.driver.find_element_by_css_selector(cssSC2).click()
            time.sleep(1)
        self.driver.find_element_by_css_selector('#passBtn').click()
        time.sleep(1)
        self.driver.find_element_by_css_selector(cssQRAN).click()
        time.sleep(3)

        self.driver.switch_to.default_content()

        cssqjcg = 'body > div > div.messager-body.panel-body.panel-body-noborder.window-body > div.messager-button > div > a'
        self.is_visible(cssqjcg)
        buttonqj1 = self.driver.find_element_by_css_selector(cssqjcg)
        time.sleep(2)
        self.driver.execute_script('$(arguments[0]).click()', buttonqj1)

    elif cjzhDis == 'true':
        time.sleep(1)
        self.driver.find_element_by_css_selector('#passBtn').click()
        time.sleep(1)
        self.driver.find_element_by_css_selector(cssQRAN).click()
        time.sleep(3)
        self.close()
        # self.driver.switch_to.default_content()
        # cssqjcg2 = 'body > div:nth-child(8) > div.messager-body.panel-body.panel-body-noborder.window-body > div.messager-button > div > a > span'
        # time.sleep(3)
        # buttonqj2 = self.driver.find_element_by_css_selector(cssqjcg2)
        # time.sleep(2)
        # self.driver.execute_script('$(arguments[0]).click()', buttonqj2)


def authByuseCode(self):

    time.sleep(1)
    # 选择一列
    cssClick = '#datagrid-row-r1-2-0 > td:nth-child(3)'

    # 生成资金账号
    cssSC1 = '#PRO_ACC_CODE > span'

    # 点击第一列
    time.sleep(2)
    # self.driver.find_element_by_css_selector(cssClick).click()
    self.browerClick(cssClick)

    time.sleep(1)
    # 确认按钮
    cssQRAN = "body > div.panel.window.messager-window > div.messager-body > div > div:nth-child(1) > a"

    # 获取是否有资金账号,此处选切回默认然后再到切一次

    self.ifrmaeSwitchDefault()
    self.ifrmaeSwitch('iframe[src*=review]')

    #两融客户生成资金帐号
    time.sleep(3)
    if self.is_element_exist(cssSC1) :
        self.browerClick(cssSC1)


    #点击通过
    self.browerClick('#passBtn')
    self.my_print_info('current time %s' % currtime)
    time.sleep(1)

    self.driver.switch_to.default_content()
    self.ifrmaeSwitch('iframe[src*=review]')

    cssqjcg1 = 'body > div.panel.window.messager-window > div.messager-body.panel-body.panel-body-noborder.window-body > div.messager-button > div:nth-child(1) > a'

    cssqjcg2  = 'body > div > div.messager-body.panel-body.panel-body-noborder.window-body > div.messager-button > div:nth-child(1) > a > span'



    if  self.is_visible(cssqjcg1):
        cssqjcg = cssqjcg1
    elif self.is_visible(cssqjcg2):
        cssqjcg = cssqjcg2


    buttonqj1 = self.driver.find_element_by_css_selector(cssqjcg)
    time.sleep(2)
    self.driver.execute_script('$(arguments[0]).click()', buttonqj1)
    time.sleep(2)
    self.driver.switch_to.default_content()
    time.sleep(2)

    # cssqjcg = 'body > div > div.messager-body.panel-body.panel-body-noborder.window-body > div.messager-button > div > a'
    csszhqr1 = 'body > div.panel.window.messager-window > div.messager-body.panel-body.panel-body-noborder.window-body > div.messager-button > div > a > span'
    csszhqr2 = 'body > div > div.messager-body.panel-body.panel-body-noborder.window-body > div.messager-button > div > a > span'

    time.sleep(1)
    if self.is_visible(csszhqr1):
        self.browerClick(csszhqr1)
    elif self.is_visible(csszhqr2):
        self.browerClick(csszhqr2)

def inputMobile2(self, hj, cssDH, cssAN, cssYZM):
    '''通过方法来输入手机号码,依次输入环境fat或uat电话号码css,点击按钮css,验证码css'''

    try:
        # 调用函数生成号码
        valTel = self.autoPhone18()
        vStart = valTel[:3]
        vEnd = valTel[7:11]
        print(valTel)
        # 电话
        self.driver.find_element_by_css_selector(cssDH).clear()
        self.driver.find_element_by_css_selector(cssDH).send_keys(valTel)
        time.sleep(2)
        self.executeJSClick(cssAN)
        time.sleep(2)
        cssFlag = 'body > div.panel.window.messager-window > div.panel-header.panel-header-noborder.window-header > div.panel-title'

        self.is_visible(cssFlag)

        cssWind = "body > div.panel.window.messager-window > div.messager-body.panel-body.panel-body-noborder.window-body > div.messager-button > div > a"

        self.executeJSClick(cssWind)

        import cx_Oracle
        if hj == 'fat':
            db = cx_Oracle.connect(globaDB.dbfat)
        elif hj == 'uat':
            db = cx_Oracle.connect(globaDB.dbuat)

        time.sleep(1)
        cursor = db.cursor()
        sql = "select sms_code from (select sms_code from opp_busi_sms  order by oper_time desc) where rownum=1"

        self.my_print_info(sql)
        time.sleep(1)
        rs = cursor.execute(sql)
        li = rs.fetchall()
        time.sleep(1)
        # # 打印业务单号,此处引用正则来过滤到数字,去掉其它字符
        code = li[0][0]
        # code = li[3:9]

        print(code)
        db.close()
        time.sleep(1)
    finally:
        self.driver.find_element_by_css_selector(cssYZM).send_keys(code)
        time.sleep(1)



def recognitionCust(self, custCode, passVal):
    # 识别客户代码
    # self.driver.switch_to.frame(self.driver.find_element_by_css_selector('iframe[src*=cust-recognite]'))
    self.ifrmaeSwitch('iframe[src*=cust-recognite]')
    time.sleep(2)
    # 输入客户代码来进行识别
    self.driver.find_element_by_css_selector('#IDENT_CODE').clear()
    self.driver.find_element_by_css_selector('#IDENT_CODE').send_keys(custCode)
    self.driver.find_element_by_css_selector('#regBtn').click()
    # 选中数据占且点击
    self.driver.find_element_by_css_selector('#datagrid-row-r1-2-0').click()
    self.driver.find_element_by_css_selector('#CUACCT_PWD').send_keys(passVal)
    time.sleep(1)
    # 确认按钮
    cssQRAN = 'body > div.panel.window > div.panel-body.panel-body-noborder.window-body > div.dialog-button > div:nth-child(1) > a'
    self.driver.find_element_by_css_selector(cssQRAN).click()

def enterMenu(self, menu):
    '''管理员业务中进入数字菜单,需要输入菜单序列号'''
    self.ifrmaeSwitchDefault()

    self.is_not_visible("body > div.panel.window.messager-window.message-loading > div")
    self.ifrmaeSwitch('iframe[src*=pages]')

    # 进入菜单
    cssInput = 'body > div.biz-nav-new.clearfix > div.menu-search-wrap > div.menu-search-box > input'
    cssSelect = 'body > div.biz-nav-new.clearfix > div.menu-search-wrap > div.menu-search-box > div > ul > li[data-menu-name="%s"]'%(menu)
    self.driver.find_element_by_css_selector(cssInput).send_keys(menu)
    time.sleep(1)
    print(cssSelect)
    #选择对应的菜单
    self.driver.find_element_by_css_selector(cssSelect).click()

    self.ifrmaeSwitchDefault()

    self.is_not_visible("body > div.panel.window.messager-window.message-loading > div")

    self.ifrmaeSwitch('iframe[src*=apps]')

def updatFlowStatus(self,cuacct):

    #修改流程状态

    userCode = self.selectUsercode(cuacct)
    #先调用方法生成usercode
    self.my_print_info(userCode)

    import cx_Oracle

    if globaVar.event == 'fat':
        db = cx_Oracle.connect(globaDB.dbfat)
        #print globaDB.dbfat
    elif globaVar.event == 'uat':
        db = cx_Oracle.connect(globaDB.dbuat)
        #print globaDB.dbuat
    time.sleep(1)

    cursor = db.cursor()
    sql = "update opp_busi_data set proc_status = '15' where cust_code = \'%s\' and proc_status != '13'" % userCode
    print(sql)
    cursor.execute(sql)
    db.commit()
    cursor.close()
    db.close()

def updatZDStatus(self,cuacct):

    #修改流程状态

    userCode = self.selectUsercode(cuacct)
    #先调用方法生成usercode

    import cx_Oracle

    db = cx_Oracle.connect(globaDB.dbuatAccount)
    time.sleep(1)

    cursor = db.cursor()
    sql = "update STK_TRDACCT set TREG_STATUS = '2' where CUST_CODE =  \'%s\' and STKEX = '1'" % userCode
    print(sql)
    cursor.execute(sql)
    db.commit()
    cursor.close()
    db.close()

def selectUsercode(self,cuacct):

    #通过资金帐号查找客户代码,使用帐户的数据库,此功能可扩展待续
    import cx_Oracle
    db = cx_Oracle.connect(globaDB.dbuatAccount)
    time.sleep(1)
    cursor = db.cursor()
    sql = "select cust_code from stk_trdacct where cuacct_code =\'%s\'" % cuacct
    rs = cursor.execute(sql)
    li = rs.fetchall()
    time.sleep(1)
    code = str(li)[2:11]
    cursor.close()
    db.close()
    return code







def getPubStaticAccess(self):
    '''获取静态准入,待优化'''
    self.ifrmaeSwitch('iframe[src*=apps]')

    if self.is_element_exist('#accessBanTip'):
        # 禁止

        lists = self.driver.find_element_by_css_selector('#accessBanTip').find_elements_by_css_selector(
            'div.item-row-word')
        time.sleep(3)
        print(self.driver.text)
        print(len(lists))
        print(self.driver.find_element_by_css_selector('#accessBanTip > div.item-title').text)
        for i in range(len(lists)):
            print(lists[i].text)
    elif self.is_element_exist('#accessWarnTip'):
        # 警告

        lists = self.driver.find_element_by_css_selector('#accessWarnTip').find_elements_by_css_selector(
            'div.item-row-word')
        time.sleep(3)
        print(self.driver.title)
        print(len(lists))
        print(self.driver.find_element_by_css_selector('#accessWarnTip > div.item-title').text)
        for i in range(len(lists)):
            print(lists[i].text)
    elif self.is_element_exist('#accessPromptTip'):
        # 提示

        lists = self.driver.find_element_by_css_selector('#accessPromptTip').find_elements_by_css_selector(
            'div.item-row-word')
        time.sleep(3)
        print(self.driver.title)
        print(len(lists))
        print(self.driver.find_element_by_css_selector('#accessPromptTip > div.item-title').text)
        for i in range(len(lists)):
            print(lists[i].text)
    elif self.is_element_exist('#msgTip > div.tip-content > span'):
        print(self.driver.find_element_by_css_selector('#msgTip > div.tip-content > span').text)

猜你喜欢

转载自blog.csdn.net/qq_24790545/article/details/82495102