1

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!

1

1 Answer 1

1

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']]
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.