无法在try / except中记录Selenium浏览器错误

时间:2018-01-11 22:05:09

标签: python selenium selenium-webdriver selenium-chromedriver

我正在编写一个python脚本来测试我是否能够登录到网址并验证网页上的元素。

当有任何错误时,我想从Selenium捕获日志。

我的挑战是每当我在write_logs异常中调用NoSuchElementException函数时,写入的日志都是空白的。

有什么明显的东西我不见了吗?

import os
import json
from selenium import webdriver
from selenium.webdriver.common.desired_capabilities import DesiredCapabilities
from selenium.common.exceptions import NoSuchElementException


# function that writes logs to file system
def write_logs(driver):
    log = driver.get_log('browser')
    with open('selenium_browser.log', 'w') as outfile:
        json.dump(log, outfile, indent=4)

baseurl = 'https://example.com'

username = os.environ.get('USER')
password = os.environ.get('PASSWORD')

xpaths = {'usernameTxtBox': "//input[@name='Username']",
          'passwordTxtBox': "//input[@name='Password']",
          'submitButton': "//input[@id='loginButton']"
          }
validate_url = 'https://example.com/page_only_accessible_once_logged_in'

d = DesiredCapabilities.CHROME
d['loggingPrefs'] = {'browser': 'ALL'}

driver = webdriver.Chrome(desired_capabilities=d)

driver.implicitly_wait(10)
driver.get(baseurl)

driver.find_element_by_xpath(xpaths['usernameTxtBox']).clear()
driver.find_element_by_xpath(xpaths['usernameTxtBox']).send_keys(username)

driver.find_element_by_xpath(xpaths['passwordTxtBox']).clear()
driver.find_element_by_xpath(xpaths['passwordTxtBox']).send_keys(password)
driver.find_element_by_xpath(xpaths['submitButton']).click()

try:
    logged_in = driver.find_element_by_xpath('//*[@id="idLoggedInTitle"]')
except NoSuchElementException:
    write_logs(driver)
    driver.close()
    exit("can't login")


try:
    driver.get(validate_url)
    element = driver.find_element_by_xpath('//*[@id="titleView!1Title"]')
    print(element.text)
except NoSuchElementException:
    write_logs(driver)
    driver.close()
    exit("Not able to reach url")

write_logs(driver)
driver.close()

print("completed sucessfully")

1 个答案:

答案 0 :(得分:1)

目前您正在使用log = driver.get_log('browser')创建日志,该日志仅捕获浏览器错误,而不是硒错误。如果您需要在搜索NoSuchElementException时记录引发的{selenium driver.find_element_by_xpath('//*[@id="titleView!1Title"]'),则需要捕获回溯。

import traceback

def write_logs(driver, error_message, stack_trace):
    # print the error message and stack and see if that's what you want to log
    print (error_message + '\n' + stack_trace)
    # if it is, add it to your outfile how you want to record it
    with open('selenium_browser.log', 'w') as outfile:
        outfile.write(error_message + '\n' + stack_trace)

try:
    driver.get(validate_url)
    element = driver.find_element_by_xpath('//*[@id="titleView!1Title"]')
    print(element.text)
except NoSuchElementException as e:
    error_message = str(e)
    stack_trace = str(traceback.format_exc())
    write_logs(driver, error_message, stack_trace)
    driver.close()
    exit("Not able to reach url")