Search code examples
pythongoogle-chromeselenium-webdriverselenium-chromedriverwebdriver

grabbing console log output for a chrome browser using python and selenium


Title sums it up really. I'm completely new to using selenium with python. Using a python script, I'm trying to run a command on a website's console, then I'm trying to retrieve the output from that command to be used by my python script.

from selenium import webdriver
from selenium.webdriver.common.by import By

chromedriver = "path to driver"
driver = webdriver.Chrome(executable_path=chromedriver)

# load some site
driver.get('http://example.com') #orignally I used foo.com but stackoverflow doesn't like that

driver.execute_script("console.log('hello world')")
# print messages
for entry in driver.get_log('browser'):
    print(entry)

but this doesn't return anything

Upon performing an inspect element on the page opened and going to the console. I saw that my hello world message was indeed there.

enter image description here

But I have no idea why this isn't being returned by my code. Any help would be super appreciated, thankyou!


Solution

  • Here's how to save the console logs and print them out:

    from selenium import webdriver
    
    driver = webdriver.Chrome()
    
    driver.execute_script("""
        console.stdlog = console.log.bind(console);
        console.logs = [];
        console.log = function(){
            console.logs.push(Array.from(arguments));
            console.stdlog.apply(console, arguments);
        }
        """)
    
    driver.execute_script("console.log('hello world ABC')")
    driver.execute_script("console.log('hello world 123')")
    
    print(driver.execute_script("return console.logs"))
    
    driver.quit()
    

    Here's the output of that:

    [['hello world ABC'], ['hello world 123']]