Python异常截图

Python异常截图

import os
import time
import traceback
from datetime import datetime
import pymysql
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.support.ui import WebDriverWait
from logs import logger


class DB():
    def __init__(self):
        self._conn()

    def _conn(self):
        try:
            host = "localhost"
            port = 3306
            user = "root"
            password = "password"
            db = "db"
            self.conn = pymysql.connect(host=host, port=port, user=user, password=password, db=db, charset='utf8')
            return True
        except:
            return False

    def _reConn(self, num=28800, stime=1):  
        _number = 0
        _status = True
        while _status and _number <= num:
            try:
                self.conn.ping()  
                _status = False
            except:
                if self._conn() == True:  
                    _status = False
                    break
                _number += 1
                time.sleep(stime)  

    def ExcuseSql(self, sql):  
        self._reConn()
        if "select" in sql.lower():
            return self.Select(sql)
        else:
            return self.Insert(sql)

    def Select(self, sql):
        try:
            cursor = self.conn.cursor()
            cursor.execute(sql)
            data = cursor.fetchall()
            self.conn.close()
            return data
        except Exception as e:
            print(sql)
            traceback.print_exc()

    def Insert(self, sql):
        try:
            cursor = self.conn.cursor()
            cursor.execute(sql)
            effectRow = cursor.rowcount
            self.conn.commit()
            self.conn.close()
            return effectRow
        except Exception as e:
            print(sql)
            traceback.print_exc()

    def InsertPath(self, url):
        CreateTimes = datetime.now().strftime("%Y-%m-%d %H:%M:%S.%f")
        self.ExcuseSql("INSERT INTO `db`.`path`(`CreateTimes`, `url`) VALUES ('%s', '%s')" % (CreateTimes, url))

    def InsertBase64(self, base64):
        CreateTimes = datetime.now().strftime("%Y-%m-%d %H:%M:%S.%f")
        self.ExcuseSql("INSERT INTO `db`.`base64`(`CreateTimes`, `base64`) VALUES ('%s', '%s')" % (CreateTimes, base64))


class Data:

    def __init__(self):
        self.driver = webdriver.Firefox()
        self.db = DB()
        logger.info('__ScreenShot__init__')

    def __Sendkeys__(self, Xpath, keys):
        try:
            WebDriverWait(self.driver, 2).until(EC.presence_of_element_located((By.XPATH, Xpath)))  # 显示等待
            self.driver.find_element_by_xpath(Xpath).send_keys(keys)
        except:
            self.get_screenshoot_as_file()  # 异常截图,截图以png的形式保存至文件夹
            logger.info('Insert url success')
            str = self.driver.get_screenshot_as_base64()  # 异常截图,截图以base64的形式保存至数据库
            self.db.InsertBase64(str)
            logger.info('Insert base64 success')

    def __Click__(self, Xpath):
        WebDriverWait(self.driver, 2).until(EC.presence_of_element_located((By.XPATH, Xpath)))  # 显示等待
        self.driver.find_element_by_xpath(Xpath).click()

    def get_screenshoot_as_file(self):  # 异常截图方法,截图以png的形式保存至文件夹
        path = os.path.dirname(os.getcwd()) + '/picture/'
        timestamp = time.strftime("%Y%m%d%H%M%S")  # 字符串类型时间戳
        filename = path + timestamp + '.png'
        self.db.InsertPath(filename)
        return self.driver.get_screenshot_as_file(filename)

    def Run(self):
        try:
            self.driver.get("http://localhost:8080/login/")  # 百度账号登录
            # time.sleep(1)  # 强制等待看页面显示结果
            self.__Sendkeys__("//input[@id='user']", "username")
            self.__Sendkeys__("//input[@id='psw']", "password")
            self.__Click__("//*[@id='btn']")
            logger.info('Success')
            time.sleep(0.5)
            self.driver.quit()
        except Exception as e:
            print("str(Exception):" + str(Exception))
            logger.error(str(Exception))
            print("")

            print("str(e):" + str(e))
            logger.error(str(e))

            print("repr(e):" + repr(e))
            logger.error(repr(e))
            print("")

            print("traceback.print_exc():")
            print("")

            print("traceback.format_exc():")
            print(traceback.format_exc())
            logger.error(traceback.format_exc())

            print("traceback.print_exception():")
            traceback.print_exception()
            logger.error(traceback.print_exception())


if __name__ == "__main__":
    dt = Data()
    dt.Run()
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值