在自动化测试过程中,日志是非常重要的一个部分,特别是当运行出现错误时,需要查看日志来分析定位解决问题。
实例
下面通过一个实例来捕捉日志。
- 自动打开百度
- 搜索selenium
首先创建日志配置文件log.conf
添加如下配置内容:
log.conf
[loggers]
keys=root,infoLogger
[logger_root]
level=DEBUG
handlers=consoleHandler,fileHandler
[logger_infoLogger]
handlers=consoleHandler,fileHandler
qualname=infoLogger
propagate=0
###############################################
[handlers]
keys=consoleHandler,fileHandler
[handler_consoleHandler]
class=StreamHandler
level=INFO
formatter=form02
args=(sys.stdout,)
[handler_fileHandler]
class=FileHandler
level=INFO
formatter=form01
args=('mylog.log', 'a')
###############################################
[formatters]
keys=form01,form02
[formatter_form01]
format=%(asctime)s %(filename)s[line:%(lineno)d] %(levelname)s %(message)s
datefmt=%Y-%e-%d %H:%M:%S
[formatter_form02]
format=%(asctime)s %(filename)s[line:%(lineno)d] %(levelname)s %(message)s
datefmt=%Y-%e-%d %H:%M:%S
其次创建.py文件加载配置文件如创建:test_log.py文件
test_log.py
# 导入日志模块
import logging
import logging.config
from selenium import webdriver
# 加载日志配置文件
CON_LOG = 'log.conf' #注意是log.conf所在路径
logging.config.fileConfig(CON_LOG)
logging = logging.getLogger()
# 打开百度
driver = webdriver.Firefox()
driver.get('http://www.baidu.com')
try:
# 输出日志
logging.info('baidu selenium')
driver.find_element_by_id('kw').send_keys('selenium')
driver.find_element_by_id('su').click()
logging.info('succeed')
except Exception as e:
# 输出报错日志
logging.error(e)
finally:
driver.close()
运行结果
2018-30-30 14:15:48 test_log.py[line:12] INFO baidu selenium
2018-30-30 14:15:48 test_log.py[line:15] INFO succeed
进程已结束,退出代码0
日志文件截图
日志文件
下面来看看出错的情况日志的输出格式
# 改成错误的id
driver.find_element_by_id('kw1').send_keys('selenium')
运行结果
2018-30-30 14:20:16 test_log.py[line:12] INFO baidu selenium
2018-30-30 14:20:16 test_log.py[line:17] ERROR Message: Unable to locate element: [id="kw1"]
进程已结束,退出代码0
日志文件
日志文件
如果想看更详细的日志信息,可以修改如下代码
# 增加一个参数exc_info=1
logging.error(e, exc_info=1)
运行结果
2018-30-30 14:23:23 test_log.py[line:12] INFO baidu selenium
2018-30-30 14:23:23 test_log.py[line:17] ERROR Message: Unable to locate element: [id="kw1"]
Traceback (most recent call last):
File "F:/PycharmProjects/untitled7/test_log.py", line 13, in <module>
driver.find_element_by_id('kw1').send_keys('selenium')
File "C:\Python35\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 285, in find_element_by_id
return self.find_element(by=By.ID, value=id_)
File "C:\Python35\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 787, in find_element
'value': value})['value']
File "C:\Python35\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 252, in execute
self.error_handler.check_response(response)
File "C:\Python35\lib\site-packages\selenium\webdriver\remote\errorhandler.py", line 194, in check_response
raise exception_class(message, screen, stacktrace)
selenium.common.exceptions.NoSuchElementException: Message: Unable to locate element: [id="kw1"]
网友评论