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()
logger.info('Insert url success')
str = self.driver.get_screenshot_as_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):
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/")
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()