예제 #1
0
class ReadExcel(object):
    # 参数excel_path是文件的绝对路径,sheet_name是表名
    def __init__(self, excel_path, sheet_name="Sheet1"):
        self.data = xlrd.open_workbook(excel_path)  # 根据路径打开一个文件
        self.table = self.data.sheet_by_name(sheet_name)  # 根据表名打开表
        self.keys = self.table.row_values(0)  # 获取第一行作为字典的key值
        self.rowNum = self.table.nrows  # 获取总行数
        self.colNum = self.table.ncols  # 获取总列数
        self.log = Log("读取excel").get_logger()

    # 获取整张表的数据(数据装在列表中,列表的每个子元素是字典类型数据)
    def get_dict_data(self):
        if self.rowNum <= 1:
            self.log.error('xlsx表的总行数小于1')
        else:
            r = []  # 定义列表变量,把读取的每行数据拼接到此列表中

            for row in range(1, self.rowNum):  # 对行进行循环读取数据,从第二行开始
                s = {}  # 定义字典变量
                s['rowNum'] = row + 1  # 存储行数,从第二行开始读,行数等于下标加1
                values = self.table.row_values(row)  # 获取行的数据

                for col in range(0, self.colNum):  # 对列进行循环读取数据
                    cell_value = values[col]
                    if isinstance(cell_value, (int, float)):  # 判断读取数据是否是整型或浮点型
                        cell_value = int(cell_value)  # 是,数据转换为整数

                    s[self.keys[col]] = str(
                        cell_value).strip()  # 获取到单元格数据(去掉头尾空格)和key组成键对值
                r.append(s)  # 把获取到行的数据装入r列表中
            return r  # 返回整个表的数据
예제 #2
0
class PdfJar(object):
    def __init__(self):
        self.log = Log().get_logger()
        self.path = r'C:\AProjectCode\Python\python3_interface\study_case\data\开发指南.pdf'
        self.out_path = r'C:\AProjectCode\Python\python3_interface\study_case\data\开发指南.txt'

    def startJvm(self):
        return JVMStart().start_jvm(['pdfbox-app-2.0.12.jar'])

    def get_java_objecj(self):
        self.file = JClass("java.io.File")
        self.FileOutputStream = JClass("java.io.FileOutputStream")
        self.OutputStreamWriter = JClass("java.io.OutputStreamWriter")
        self.Writer = JClass("java.io.Writer")
        self.PDDocument = JClass("org.apache.pdfbox.pdmodel.PDDocument")
        self.PDFTextStripper = JClass("org.apache.pdfbox.text.PDFTextStripper")

    def get_txt(self):
        try:
            self.get_java_objecj()
            input = self.file(self.path)  # 转换文件为File类型
            document = self.PDDocument.load(input)  # 加载pdf文件
            outputStream = self.FileOutputStream(self.out_path)
            output = self.OutputStreamWriter(outputStream, 'UTF-8')  # 文件输出流
            stripper = self.PDFTextStripper()  #  PDFTextStripper来提取文本
            stripper.setSortByPosition(False)  # 设置是否排序
            stripper.setStartPage(1)  # 设置起始页
            stripper.setEndPage(100000)  # 设置结束页
            stripper.writeText(document,
                               output)  # 调用PDFTextStripper的writeText提取并输出文本
            self.log.info(stripper.getText(document))  # 直接获取text

            output.close()  # 关闭输出流
            document.close()
        except Exception as e:
            self.log.error('出现异常:%s' % e)

    def shutdownJVM(self):
        JVMStart().shutdown_jvm()
예제 #3
0
class BasePage(object):
    """
        定义一个页面基类,让所有页面都继承这个类,封装一些常用的页面操作方法到这个类
    """
    def __init__(self, url):
        self.log = Log().get_logger()
        self.url = url
        # 启动浏览器
        self.driver = webdriver.Ie()
        # self.driver = webdriver.Edge()
        # self.driver = webdriver.Firefox()
        # self.driver = webdriver.Chrome()
        self.driver.get(self.url)
        self.driver.maximize_window()
        #driver.implicitly_wait(5)  # 隐式等待

    def get_driver(self):
        return self.driver

    def max_window(self):
        self.driver.maximize_window()

    def set_window(self, wide, high):
        self.driver.set_window_size(wide, high)

    # 退出浏览器
    def quit(self):
        self.driver.quit()

    # 浏览器前进操作
    def forward(self):
        self.driver.forward()

    # 浏览器后退操作
    def back(self):
        self.driver.back()

    # 隐式等待
    def wait(self, seconds):
        self.driver.implicitly_wait(seconds)

    # 点击关闭当前窗口
    def close(self):
        try:
            self.driver.close()
        except Exception as e:
            self.log.error("Failed to quit the browser with %s" % e)

    # 获取当前网页的标题
    def get_title(self):
        return self.driver.title

    # 获取当前网页的url
    def get_url(self):
        return self.driver.current_url

    @staticmethod
    def sleep(seconds):
        time.sleep(seconds)

    # 清除文本框
    def clear(self, selector):
        try:
            el = self.element_wait(selector)
            el.clear()
        except Exception as e:
            self.log.error("Failed to clear in input box with %s" % e)
            self.take_screenshot('clear_failure')

    # 直接输入
    def type(self, css, text):
        try:
            el = self.element_wait(css)
            el.send_keys(text)
        except Exception as e:
            self.log.error("Failed to type in input box with %s" % e)
            self.take_screenshot('input_box_failure')
            raise

    # 清空并输入
    def clear_type(self, css, text):
        try:
            el = self.element_wait(css)
            el.clear()
            el.send_keys(text)
        except Exception as e:
            self.log.error("Failed to type in input box with %s" % e)
            self.take_screenshot('input_box_failure')
            raise

    # 点击元素
    def click(self, selector):
        try:
            el = self.element_wait(selector)
            el.click()
        except Exception as e:
            self.log.error("Failed to click the element with %s" % e)
            self.take_screenshot('click_failure')
            raise

    # 右键
    def right_click(self, css):
        try:
            el = self.element_wait(css)
            ActionChains(self.driver).context_click(el).perform()
        except Exception as e:
            self.log.error("Failed to click the element with %s" % e)
            self.take_screenshot('right_click_failure')
            raise

    # 双击
    def double_click(self, css):
        try:
            el = self.element_wait(css)
            ActionChains(self.driver).double_click(el).perform()
        except Exception as e:
            self.log.error("Failed to click the element with %s" % e)
            self.take_screenshot('double_click_failure')
            raise

    # 鼠标移到指定元素上
    def move_to_element(self, css):
        try:
            el = self.element_wait(css)
            ActionChains(self.driver).move_to_element(el).perform()
        except Exception as e:
            self.log.error("Failed to move to the element with %s" % e)
            self.take_screenshot('move_to_failure')
            raise

    # 拖拽到某个元素然后松开
    def drag_and_drop(self, el_css, ta_css):
        try:
            element = self.element_wait(el_css)
            target = self.element_wait(ta_css)
            ActionChains(self.driver).drag_and_drop(element, target).perform()
        except Exception as e:
            self.log.error("Failed to drag_and_drop with %s" % e)
            self.take_screenshot('drag_and_drop_failure')
            raise

    #  Submit the specified form.
    def submit(self, css):
        try:
            el = self.element_wait(css)
            el.submit()
        except Exception as e:
            self.log.error("Failed to submit with %s" % e)
            self.take_screenshot('submit_failure')
            raise

    # f5 刷新
    def F5(self):
        self.driver.refresh()

    def js(self, script):
        """
        Usage: driver.js("window.scrollTo(200,1000);")
        """
        try:
            self.driver.execute_script(script)
        except Exception as e:
            self.log.error("Failed to js with %s" % e)
            self.take_screenshot('js_failure')
            raise

    # 获取元素的属性
    def get_attribute(self, css, attribute):
        try:
            el = self.element_wait(css)
            return el.get_attribute(attribute)
        except Exception as e:
            self.log.error("Failed to get_attribute with %s" % e)
            self.take_screenshot('get_attribute_failure')
            raise

    # 获取元素的文本信息
    def get_text(self, css):
        try:
            return self.element_wait(css).text
        except Exception as e:
            self.log.error("Failed to get_text with %s" % e)
            self.take_screenshot('get_text_failure')
            raise

    # 切换到指定的警告弹窗口并点击确认
    def accept_alert(self):
        self.driver.switch_to.alert.accept()

    # 切换到指定的警告弹窗口并点击取消
    def dismiss_alert(self):
        self.driver.switch_to.alert.dismiss()

    # 切换到指定的帧视图
    def switch_to_frame(self, css):
        try:
            iframe_el = self.element_wait(css)
            self.driver.switch_to.frame(iframe_el)
        except Exception as e:
            self.log.error("Failed to switch_to_frame with %s" % e)
            self.take_screenshot('switch_to_frame_failure')
            raise

    # 退出当前的帧视图
    def switch_to_frame_out(self):
        self.driver.switch_to.default_content()

    # 打开并切换到新窗口
    def open_new_window(self, css):
        try:
            original_windows = self.driver.current_window_handle
            self.element_wait(css).click()  # 点击元素打开新窗口
            all_handles = self.driver.window_handles
            for handle in all_handles:
                if handle != original_windows:
                    self.driver.switch_to.window(handle)  # 切换到新窗口
        except Exception as e:
            self.log.error("Failed to open_new_window with %s" % e)
            self.take_screenshot('open_new_window_failure')
            raise

    # 判断元素是否存在
    def element_exist(self, css):
        try:
            self.element_wait(css)
            return True
        except TimeoutException:
            return False

    # 保存图片
    def take_screenshot(self, name):
        now_time = time.strftime('%Y%m%d') + '_'
        screen_name = config.test_screenshot_path + now_time + name + '.png'
        try:
            self.driver.get_screenshot_as_file(screen_name)
        except Exception as e:
            self.log.error("Failed to take screenshot! %s" % e)
            raise

    def type_and_enter(self, css, text, secs=0.5):
        """
        Operation input box. 1、input message,sleep 0.5s;2、input ENTER.
        """
        try:
            ele = self.element_wait(css)
            ele.send_keys(text)
            time.sleep(secs)
            ele.send_keys(Keys.ENTER)
        except Exception as e:
            self.log.error("Failed to type_and_enter with %s" % e)
            self.take_screenshot('type_and_enter_failure')
            raise

    def js_click(self, css):
        try:
            js_str = "$('{0}').click()".format(css)
            self.driver.execute_script(js_str)
        except Exception as e:
            self.log.error("Failed to js_click with %s" % e)
            self.take_screenshot('js_click_failure')
            raise

    # 定位元素方法
    def get_element(self, css):
        """
         根据=>来切割字符串
        """
        if '=>' not in css:
            raise NameError("Positioning syntax errors, lack of '=>'.")

        by = css.split('=>')[0]
        value = css.split('=>')[1]

        if by == "i" or by == 'id':
            element = self.driver.find_element_by_id(value)
        elif by == "n" or by == 'name':
            element = self.driver.find_element_by_name(value)
        elif by == "c" or by == 'class':
            element = self.driver.find_element_by_class_name(value)
        elif by == "l" or by == 'link_text':
            element = self.driver.find_element_by_link_text(value)
        elif by == "p" or by == 'partial_link_text':
            element = self.driver.find_element_by_partial_link_text(value)
        elif by == "x" or by == 'xpath':
            element = self.driver.find_element_by_xpath(value)
        elif by == "s" or by == 'css':
            element = self.driver.find_element_by_css_selector(value)
        else:
            raise NameError(
                "elements must is,'id','name','class','link_text','partial_link_text',xpaht','css'."
            )
        return element

    # 显式等待
    def element_wait(self, css, secs=5):
        """
        等待元素显示
        Usage:
        driver.element_wait("id->kw",10)
        """
        if "=>" not in css:
            raise NameError("Positioning syntax errors, lack of '=>'.")

        by = css.split("=>")[0].strip()
        value = css.split("=>")[1].strip()
        messages = 'Element: {0} not found in {1} seconds.'.format(css, secs)

        if by == "i" or by == 'id':
            element = WebDriverWait(self.driver, secs, 1).until(
                EC.presence_of_element_located((By.ID, value)), messages)
        elif by == "n" or by == 'name':
            element = WebDriverWait(self.driver, secs, 1).until(
                EC.presence_of_element_located((By.NAME, value)), messages)
        elif by == "c" or by == 'class':
            element = WebDriverWait(self.driver, secs, 1).until(
                EC.presence_of_element_located((By.CLASS_NAME, value)),
                messages)
        elif by == "l" or by == 'link_text':
            element = WebDriverWait(self.driver, secs, 1).until(
                EC.presence_of_element_located((By.LINK_TEXT, value)),
                messages)
        elif by == "p" or by == 'partial_link_text':
            element = WebDriverWait(self.driver, secs, 1).until(
                EC.presence_of_element_located((By.PARTIAL_LINK_TEXT, value)),
                messages)
        elif by == "x" or by == 'xpath':
            element = WebDriverWait(self.driver, secs, 1).until(
                EC.presence_of_element_located((By.XPATH, value)), messages)
        elif by == "s" or by == 'css':
            element = WebDriverWait(self.driver, secs, 1).until(
                EC.presence_of_element_located((By.CSS_SELECTOR, value)),
                messages)
        else:
            raise NameError(
                "elements must is,'id','name','class','link_text','partial_link_text','xpaht','css'."
            )
        return element
예제 #4
0
class basePage(object):

    def __init__(self,driver):
        self.driver = driver
        self.timeout = 10
        self.log = Log()

    def find_element_xpath(self,xpath):
        try:
            element = WebDriverWait(self.driver, self.timeout, 0.5).until(EC.presence_of_element_located((By.XPATH,xpath)))
            self.log.info(xpath+",xpath定位成功")
            return element
        except TimeoutException:
            self.log.error("请重新定位,"+"原始定位是:"+xpath)
            self.save_screen_picture()
            return False

    def find_element_id(self,id):
        try:
            element = WebDriverWait(self.driver, self.timeout, 0.5).until(EC.presence_of_element_located((By.ID,id)))
            self.log.info(id+",id定位成功")
            return element
        except TimeoutException:
            self.log.error("请重新定位,"+"原始定位是:"+id)
            self.save_screen_picture()
            return False

    def find_element_class(self,CLASS):
        try:
            element = WebDriverWait(self.driver, self.timeout, 0.5).until(EC.presence_of_element_located((By.CLASS_NAME,CLASS)))
            self.log.info(CLASS+",class定位成功")
            return element
        except TimeoutException:
            self.log.error("请重新定位,"+"原始定位是:"+CLASS)
            self.save_screen_picture()
            return False

    def find_element_css(self,css):
        try:
            element = WebDriverWait(self.driver, self.timeout, 0.5).until(EC.presence_of_element_located((By.CSS_SELECTOR,css)))
            self.log.info(css+",css定位成功")
            return element
        except TimeoutException:
            self.log.error("请重新定位,"+"原始定位是:"+css)
            self.save_screen_picture()
            return False

    def find_elements_xpath(self,xpath):
        try:
            element = WebDriverWait(self.driver, self.timeout, 0.5).until(EC.presence_of_all_elements_located((By.XPATH,xpath)))
            self.log.info(",xpath定位列表成功")
            return element
        except TimeoutException:
            self.log.error("请重新定位,"+"原始定位是:"+xpath)
            self.save_screen_picture()
            return False

    def find_elements_css(self,css):
        try:
            element = WebDriverWait(self.driver, self.timeout, 0.5).until(EC.presence_of_all_elements_located((By.CSS_SELECTOR,css)))
            self.log.info(",css定位列表成功")
            return element
        except TimeoutException:
            self.log.error("请重新定位,"+"原始定位是:"+css)
            self.save_screen_picture()
            return False

    def quit(self):
        self.driver.quit()
        self.log.info('退出浏览器')

    def switch_frame(self, frame):
        try:
            self.log.info('切换frame')
            return self.driver.switch_to_frame(frame)
        except Exception:
            self.log.error("切换farme失败,"+frame+"定位不到")
            return False

    def switch_to_default(self):
        try:
            self.log.info('退出frame')
            return self.driver.switch_to_default_content()
        except Exception:
            self.log.error('切换默认失败')
            return False

    def switch_to_fatheriframe(self):
        try:
            self.log.info('切换到上一级frame')
            return self.driver.switch_to.parent_frame()
        except Exception:
            self.log.error('切换上一级farme失败')
            return False

    def comfirm(self,type):
        self.log.info("寻找弹窗")
        try:
            if type in 'yes':
                self.driver.switch_to_alert().accept()
            elif type in 'no':
                self.driver.switch_to_alert().dismiss()
            else:
                self.log.error("选择类型错误")
                raise Exception
        except Exception:
            self.log.error("没有找到弹窗")
            self.save_screen_picture()
            return False

    def save_screen_picture(self):  # 获取存放图片的文件夹路径
        picture_path = pictureDir + '\\'+ NOW() + '.png'
        try:
            self.driver.get_screenshot_as_file(picture_path)
        except Exception :
            self.log.error("截图失败")
            return False

    def switch_currenthandles(self):
        all_handles = self. driver.window_handles
        handler = self.driver.current_window_handle
        self.log.info("开始切换窗口")
        for i in all_handles:
            if i != handler:
                self.driver.switch_to.window(i)
                self.log.error("切换成功")


    def actionmouse(self,element):
        try:
            ActionChains(self.driver).move_to_element(element).perform()
            self.log.info('移动鼠标成功')
        except Exception:
            self.log.error("移动失败")
            self.save_screen_picture()
            return False

    def rollto(self, x):
        try:
            self.driver.execute_script('var q=document.documentElement.scrollTop=%s' %x)
            self.log.info('向下滚动了'+str(x))
        except Exception:
            self.log.error('滚动失败')
            return False

    #css定位loading页
    def wait_element_disappear_true(self, element, waittime=1,maxTime=30):
        timeTotal = 0
        try:
            while self.driver.find_element_by_css_selector(
                element).is_displayed() is True:
                time.sleep(waittime)
                timeTotal = waittime + timeTotal
                self.log.info('等待中: '+ element )
                if timeTotal > maxTime:
                    self.log.info("等待总时长" + timeTotal)
                    break
        except Exception:
            self.log.error("等待异常")

    # 执行js
    def execute(self, js, *args):
        try:
            self.driver.execute_script(js, *args)
            self.log.info('执行成功')
        except Exception:
            self.log.error('执行失败')