Prevent ChromeDriver from generating backtrace logs in cases of Selenium test failures

I am facing an issue with excessive logging by the ChromeDriver

Whenever a Selenium test fails, in addition to the regular error logs in the terminal, I receive backtrace messages like:

Stacktrace:
Backtrace:
    Ordinal0 [0x00B378B3+2193587]
    Ordinal0 [0x00AD0681+1771137]
    Ordinal0 [0x009E41A8+803240]
    ...

Is there a way to disable this backtrace? (preferably in Python :)

My configuration:

Windows 10    
Python 3.8.3    
Selenium 4.4.3    
Chrome: 105.0.5195.127 
ChromeDriver: 105.0.5195.52

I have already gone through the following discussions but haven't found a clear solution:
https://github.com/SeleniumHQ/selenium/issues/9977
https://bugs.chromium.org/p/chromedriver/issues/detail?id=3944

Checked options:

   service.log_file = -1
   opts.add_argument('--incognito')
   opts.add_argument('--log-level=0')
   opts.add_experimental_option('excludeSwitches', ['enable-logging'])
   driver = Chrome(service=service, options=opts, service_log_path='NUL')

Sample code snippet

from unittest import TestCase

from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions
from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.chrome.service import Service as ChromeService
from webdriver_manager.chrome import ChromeDriverManager


class SelBacktrace(TestCase):
    def setUp(self):
        service = ChromeService(ChromeDriverManager().install())
        service.log_file = -1
        opts = webdriver.ChromeOptions()
        opts.add_argument("--log-level=0")
        opts.add_experimental_option('excludeSwitches', ['enable-logging'])
        self.driver = webdriver.Chrome(service=service, options=opts, service_log_path='NUL')
        self.driver.get('https://httpbin.org/anything/')

    def tearDown(self):
        self.driver.quit()

    def test_backtrace(self):
        element_located = expected_conditions.visibility_of_element_located((By.CSS_SELECTOR, '.unexisting'))
        WebDriverWait(self.driver, 1).until(element_located)

Output example

Error
Traceback (most recent call last):
  File "C:\backtrace\test.py", line 27, in test_backtrace
    WebDriverWait(self.driver, 1).until(element_located)
  File "C:\backtrace\venv\lib\site-packages\selenium\webdriver\support\wait.py", line 90, in until
    raise TimeoutException(message, screen, stacktrace)
selenium.common.exceptions.TimeoutException: Message: 
Stacktrace:
Backtrace:
    Ordinal0 [0x0023DF13+2219795]
    Ordinal0 [0x001D2841+1779777]
    Ordinal0 [0x000E423D+803389]
    ...
    (No symbol) [0x00000000]

Process finished with exit code 1

Answer №1

To enhance the readability of basic selenium calls, you can implement a cleaner error output mechanism. Below is a comprehensive example that can be executed using pytest or pythom -m unittest (the file is named refined_raw.py):

import sys
from selenium import webdriver
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.support.ui import WebDriverWait
from unittest import TestCase

class RefinedRawSelenium(TestCase):
    # Setup method to initialize driver and configure options
    def setUp(self):
        self.driver = None
        options = webdriver.ChromeOptions()
        options.add_argument("--disable-notifications")
        if "linux" in sys.platform:
            options.add_argument("--headless")
        options.add_experimental_option(
            "excludeSwitches", ["enable-automation", "enable-logging"],
        )
        prefs = {
            "credentials_enable_service": False,
            "profile.password_manager_enabled": False,
        }
        options.add_experimental_option("prefs", prefs)
        self.driver = webdriver.Chrome(options=options)

  	# Teardown method to quit the driver
    def tearDown(self):
        if self.driver:
            try:
                if self.driver.service.process:
                    self.driver.quit()
            except Exception:
                pass

  	# Method to wait for element visibility
    def wait_for_element_visible(
        self, selector, by="css selector", timeout=5
    ):
        try:
            return WebDriverWait(self.driver, timeout).until(
                EC.visibility_of_element_located((by, selector))
            )
        except Exception:
            raise Exception(
                f"Selector {selector} was not visible after {timeout} seconds!"
            )

  	# Methods for interacting with elements
    def open(self, url):
        self.driver.get(url)

    def click(self, selector, by="css selector", timeout=5):
        el = self.wait_for_element_visible(selector, by=by, timeout=timeout)
        el.click()

    def type(self, selector, text, by="css selector", timeout=5):
        el = self.wait_for_element_visible(selector, by=by, timeout=timeout)
        el.clear()
        if not text.endswith("\n"):
            el.send_keys(text)
        else:
            el.send_keys(text[:-1])
            el.submit()

    # Assertion methods for verifying element presence and text
    def assert_element(self, selector, by="css selector", timeout=5):
        self.wait_for_element_visible(selector, by=by, timeout=timeout)

    def assert_text(self, text, selector="html", by="css selector", timeout=5):
        el = self.wait_for_element_visible(selector, by=by, timeout=timeout)
        self.assertIn(text, el.text)

    def assert_exact_text(self, text, selector, by="css selector", timeout=5):
        el = self.wait_for_element_visible(selector, by=by, timeout=timeout)
        self.assertEqual(text, el.text)

    # Test case for adding an item to the cart
    def test_add_item_to_cart(self):
        self.open("https://www.saucedemo.com")
        self.type("#user-name", "standard_user")
        self.type("#password", "secret_sauce\n")
        self.assert_element("div.inventory_list")
        self.assert_text("PRODUCTS", "span.title")
        self.click('button[name*="backpack"]')
        self.click("#shopping_cart_container a")
        self.assert_exact_text("YOUR CART", "span.title")
        self.assert_text("Backpack", "div.cart_item")
        self.click("#react-burger-menu-btn")
        self.click("a#logout_sidebar_link")
        self.assert_element("input#login-button")

When running the test with pytest, the output looks like this:

$ pytest refined_raw.py 
======================================= test session starts
platform darwin -- Python 3.10.5, pytest-7.1.3, pluggy-1.0.0
collected 1 item                                                                                   

refined_raw.py .

======================================== 1 passed in 4.62s

Running the test with python -m unittest produces the following result:

$ python -m unittest refined_raw.py 
.
----------------------------------------------------------------------
Ran 1 test in 4.199s
OK

In case you deliberately introduce a fake selector to fail the test on purpose, the output will indicate:

Exception: Selector {fake.element} was not visible after 5 seconds!

Before diving into wrapping all your selenium methods for specific outputs, consider exploring https://github.com/seleniumbase/SeleniumBase, a framework that automates these functionalities and more. (Full disclosure: This framework was developed by me over multiple years for Python and Selenium.)

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is the method to verify open transactions on a psycopg2 connection?

Is there a method to verify any active transactions on a psycopg2 connection? I plan to incorporate this check into my unit and functional tests, as Python's DB API executes implicit transactions. ...

What is the process for connecting the data from one instance of object A to the matching instance of object B?

In an effort to enhance my skills in advanced Python and OOP, I am working on a custom implementation for reading .ini files instead of using Python's configparser default access style. I find the current syntax like something = config['section&a ...

Is there a way to ensure that the Selenium Chromedriver waits for the window to be maximized before proceeding?

After experimenting with python/selenium, I encountered the need to use the "try" method. My goal is for the driver to wait until it maximizes the window before proceeding with the code. Initially, the scripts were executing without waiting for the window ...

Encountered a NoReverseMatch error in Django 1.10.2 stating that the reverse for 'django.contrib.auth.views.login' with empty arguments and keyword arguments was not found

Looking for help with a Python & Django error I'm encountering. Any guidance is appreciated. https://i.stack.imgur.com/4Cw94.png from django.shortcuts import render # Create your views here. # log/views.py from django.shortcuts import render from dja ...

The interpolation range has been exceeded by a value in x_new, resulting in a ValueError

I encountered an error with scikit-learn while using the following code snippet: my_estimator = LassoLarsCV(fit_intercept=False, normalize=False, positive=True, max_n_alphas=1e5) Interestingly, reducing max_n_alphas to 1e4 resolves this error for me. Do ...

Deducing characteristics of Azure virtual machines from text with Python Software Development Kit

Looking to automatically determine the available memory and number of vCPUs based on an Azure VM size provided as a string (e.g. "STANDARD_A4_v2"). I've searched through azure-mgmt-compute without success. I came across this post which uses a Compute ...

Divide a sequence of size N into smaller subsequences so that the total sum of each subarray is below a given value M. Ensure that the cut made minimizes the sum of the maximum element

Consider an integer array sequence a_n of length N. The goal is to divide the sequence into multiple parts, each consisting of consecutive integers from the original sequence. Each part should meet the following criteria: The sum of each part must not ex ...

How to retrieve webpage data using Python's "login with Google" authentication

Is it feasible to retrieve the content of a page with a specific URL using Python 3.x? When I visit the URL in my browser, I am only given the option to "Continue with Google." After providing my Google account credentials, I am able to access the desire ...

Is Selenium's Expected Conditions checking if an element is ready to be interacted with?

Does anyone know how to resolve the elementNotInteractable exception in selenium? I've tried using wait.until(ec.element_to_be_clickable()) However, my code still attempts to interact with elements that are not fully interactable. Could it be that I ...

I'm struggling to understand the issue with my global variables in my Python project

I’m stuck on my python school assignment and can’t seem to find the error I’m making. It’s either a global name not defined issue or syntax errors when I try different things. Hoping someone can help me out. Check out the assignment details below: ...

Utilizing Selenium to pinpoint an HTML element through xpath

Currently, I am in the midst of deciphering a colleague's slightly chaotic HTML as I work on developing a website testing program utilizing Selenium WebDriver in Java. Progress has been made thus far (thanks to some helpful insights from SO), but I ha ...

What is the best way to find an onmouseover element with Selenium in Python?

I've been attempting to scrape a website and encountered an element that reveals information in a bubble when the mouse hovers over it. I am using Selenium for web scraping, but I am unsure how to locate this specific element. After examining the pag ...

Encountered ElementNotInteractableException while trying to interact with a Twitter comment

I encountered an issue while using selenium to automate twitter comments as I was unable to send keys to certain elements. These are the steps I have taken so far: After receiving a console error message indicating selenium.common.exceptions.ElementNotInt ...

Django could not locate the designated URL

Here is the ajax call I am using: function fetchBodyHeights(seats_id) { $('[data-body-length]').html(gettext("Body length")); $('[data-weights]').html(gettext("Weights")); $('[data-wheel-drive]').html(gettext("Whe ...

Perplexing dilemma with connecting Python to MySQL

Hey folks, I'm currently diving into a Python project at my school. Let me clarify that I'm not exactly a python guru (I just stepped in to save the day on this project because no one else would, and I bravely said yes). Here's the issue I& ...

Tips for retaining the request.referer value during a redirect following an unsuccessful login attempt

Currently, I am in the process of adding authentication to an existing pyramid project. For now, I have implemented a basic setup where all pages raise HTTPForbidden until the user logs in. The exception view is set to /login, where users can enter their l ...

What causes a blank page to appear in Firefox upon initial execution with Selenium?

from selenium import webdriver from selenium.webdriver.common.keys import Keys driver = webdriver.Firefox() #driver.set_preference("browser.startup.homepage_override.mstone", "ignore") driver.get("https://url.aspx/") username = driver.find_element_by_name ...

Transformation of Python try-except (or try-catch) code block into VBA for a simple Excel-Selenium workflow

Here is a piece of code I'm working on: #Code snippet in Python try: io = myElm.get_attribute("rel") print(io) except IndexError: d_io = myElm.get_attribute("data-outcome") print(d_io) except: print ...

Shuffling the way integers behave

While browsing through this particular question on Stack Overflow, I found myself pondering: could it be possible to create a class that emulates the behavior of a random integer? Upon further exploration, I stumbled upon some customizable methods using t ...

Encountering a TCP connection timeout error (110: Connection timed out) on AWS when utilizing Scrapy

Here is the code snippet I wrote using Scrapy. import scrapy from scrapy.contrib.spiders import CrawlSpider, Rule from scrapy.selector import Selector from scrapy.contrib.linkextractors.sgml import SgmlLinkExtractor from urlparse import urljoin import pym ...