我有一个大型应用程序,我正在使用 Headless Chrome、Selenium 和 Python 来测试每个模块。我想遍历每个模块并获取在该特定模块内产生的所有 JS 控制台错误。
但是,由于每个模块都在不同的测试用例中,并且每个用例都在单独的 session 中执行,因此脚本首先必须在每个测试中登录。登录过程本身会产生许多显示在控制台中的错误。在测试每个模块时,我不希望日志中出现不相关的登录错误。
基本上,立即清除日志中的所有内容 -> 转到模块并执行某些操作 -> 获取已添加到控制台的日志。
这不可能吗?我尝试执行 driver.execute_script("console.clear()") 但控制台中的消息未被删除,并且在执行某些操作并打印日志后仍然显示与登录相关的消息。
请您参考如下方法:
2017 年和 2018 年底的状态
日志 API 不是官方的一部分 Webdriver specification还没有。
其实是requested to be defined对于 2 级规范。在 2017 年年中,只有 Chromedriver 有该命令的未记录的非标准实现。
在源代码中没有清除日志的方法:
- 公共(public) API
Webdriver.get_log() - 引用内部
Command姓名 - 转化为
RemoteConnection中的实际请求
可能的解决方法
返回的(原始)数据结构是一个字典,如下所示:
{
u'source': u'console-api',
u'message': u'http://localhost:7071/console.html 8:9 "error"',
u'timestamp': 1499611688822,
u'level': u'SEVERE'
}
它包含一个可以记住的时间戳,以便后续调用 get_log() 可以过滤较新的时间戳。
外观
class WebdriverLogFacade(object):
last_timestamp = 0
def __init__(self, webdriver):
self._webdriver = webdriver
def get_log(self):
last_timestamp = self.last_timestamp
entries = self._webdriver.get_log("browser")
filtered = []
for entry in entries:
# check the logged timestamp against the
# stored timestamp
if entry["timestamp"] > self.last_timestamp:
filtered.append(entry)
# save the last timestamp only if newer
# in this set of logs
if entry["timestamp"] > last_timestamp:
last_timestamp = entry["timestamp"]
# store the very last timestamp
self.last_timestamp = last_timestamp
return filtered
用法
log_facade = WebdriverLogFacade(driver)
logs = log_facade.get_log()
# more logs will be generated
logs = log_facade.get_log()
# newest log returned only
