Selenium to get browser console log

The browser console log, along with debugging also helps us capture errors that occurred when using a web application. Your developers will thank you when you include console errors in your bug reports. As part of running your GUI automation, it is a good habit to check and report the errors present in the browser’s console. In this post, I would like to share my learning on how to use Selenium to read the browser logs so that it would help others who are looking around for this info.


We’ll perform the following steps in this post:
1. Learn the Selenium API method to obtain the browser log
2. Get the console log
3. Examine a sample log message
4. Filter the log based on message type
5. Put it all together


1. Selenium API to get the console log
Selenium provides a get_log(log_type) method which helps you get the log for a given log type. So in order to get the browser console logs we need to use log type as browser

driver.get_log(‘browser’)

2. Get the console log
You can use the below method to get the console log

def get_browser_console_log(self):
        "Get the browser console log"
        try:
            log = self.driver.get_log('browser')
            return log
        except Exception,e:
            print("Exception when reading Browser Console log")
            print(str(e))

3. Sample log message
A sample log message would look like this
[{u'source': u'javascript', u'message': u'https://qxf2.com/selenium-tutorial-main 303:9 Uncaught TypeError: $(...) is not a function', u'timestamp': 1475757107472L, u'level': u'SEVERE'}]


4. Filter the log based on message type
You would want to filter out the log messages based on the level and get just the message from the result set. You can use the following piece of code to do this

log = self.read_browser_console_log()
log_errors = []
for entry in log:
                if entry['level']=='SEVERE':
                    log_errors.append(entry['message'])

5. Putting it all together
I have created two methods get_browser_console_log() and check_errors_console_log() which would help you to get the browser console logs and print them out.

def check_errors_console_log(self,url):
        "Function to get the browser's console log errors"
        self.driver.get(url)
        current_console_log_errors = []
        #As IE driver does not support retrieval of any logs,
        #we are bypassing the get_browser_console_log() method
        if "ie" not in str(self.driver): 
            log_errors = []
            new_errors = []
            log = self.get_browser_console_log()
            print "Console Log: ",log
            for entry in log:
                if entry['level']=='SEVERE':
                    log_errors.append(entry['message'])
 
            if current_console_log_errors != log_errors:
                #Find the difference
                new_errors = list(set(log_errors) - set(current_console_log_errors))
                #Set current_console_log_errors = log_errors
                current_console_log_errors = log_errors
 
            if len(new_errors)>0:
                print("\nBrowser console error on url: %s\nConsole error(s):%s"%(self.driver.current_url,'\n----'.join(new_errors)))
 
 
    def get_browser_console_log(self):
        "Get the browser console log"
        try:
            log = self.driver.get_log('browser')
            return log
        except Exception,e:
            print("Exception when reading Browser Console log")
            print(str(e))

At Qxf2, we converted the above code to be a decorator and use it in our framework. We will not able to share that code until we get time to write about our framework. But if you are comfortable enough with Python, we suggest you convert this method into a decorator.

Note:Internet Explorer driver does not support retrieval of logs of any kind.

And now browser console errors also are not to be spared :). Enjoy testing!

If you liked what you read, know more about Qxf2.


12 thoughts on “Selenium to get browser console log

  1. @Avinash Shetty:
    Thanks for posting this. I have tried to execute this but i’m getting empty list as browser log.
    Can you provide a real example.

  2. driver.execute_script(“console.log(‘Nothing to see here – move along.’);”)
    driver.execute_script(“console.warn(‘This is your first warning!’);”)
    driver.execute_script(“console.error(‘This is serious!!!’);”)

  3. How often do we need to call this console log capturing method created by you?
    As in if called once, does it keep on capturing all logs throughout the runtime?
    OR
    we need to call it before or after a certain test method that is likely to fail?
    if called before, will it capture the logs after that point?
    OR
    if called after, will it have some lines of log, before that point?

    Sorry if this is already covered in your document and i did not understand.

    1. Smita,
      It depends on what log information you want to capture. This method captures what ever log messages which are present in your Developer Tools-Console at that particular point of time and it doesn’t log throughout the run time. So ideally, it can be called from a test method where you expect a error message or is likely to fail.

  4. driver.execute_script(“console.log(‘Nothing to see here – move along.’);”)
    this is not working in my program. can anyone help me to figure out what is the problem I am new to selenium?

    My code:-

    import static org.junit.Assert.assertEquals;

    import java.util.concurrent.TimeUnit;

    import org.junit.*;
    import org.openqa.selenium.WebDriver;
    import org.openqa.selenium.chrome.ChromeDriver;
    import org.testng.annotations.Test;

    public class FirstSeleniumTest {

    public static void main(String…args) {

    //String url = “https://www.expedia.com/carsearch/details?date1=01%2F19%2F2019&time1=1200AM&date2=01%2F21%2F2019&time2=1145AM&styp=4&locn=New%20York%20(NYC-All%20Airports)&dpln=553248634999145056&dtyp=4&loc2=&piid=AQAQAQDxg2IOHEASjhxAEwmPbBATi4gcIBQANIAVCHHJgBzZAMsAED&totalPriceShown=29.1&searchKey=1968393991&offerQualifiers=GreatDeal&pickUpCountry=US&dropOffCountry=US&abax=12881.0%7C12882.0%7C12880.0&isQuickOffer=false&pickUpDistance=6.6&dropOffDistance=6.6&distanceUnit=Mile&dataSourceToken=D9E06EED58990CC95D140797B6CBB8A7&avgCatPR=41.53&dailyPriceShown=24.42”;
    System.setProperty(“webdriver.chrome.driver”,”/Applications/chromedriver”);
    WebDriver driver = new ChromeDriver();

    //System.setProperty(“webdriver.chrome.driver”,”D:\\List_of_Jar\\chromedriver.exe”);
    //driver.get(url);

    driver.navigate().to(“https://wwwexpediacom.integration.sb.karmalab.net/carsearch/details?date1=01%2F23%2F2019&time1=1000AM&date2=01%2F24%2F2019&time2=1100AM&styp=4&locn=Las%20Vegas%2C%20NV%20(LAS-McCarran%20Intl.)&dpln=5456204&olat=36.085393&dtyp=4&loc2=&piid=AgAQAIjPAFEPjEwgEY1NDCASIMCDYQAhit0gYgrdIGKggIAxABGLaGAg%2CAQAQAKBggBEAEYARoECAEQAA&totalPriceShown=64.67&searchKey=1638651872&offerQualifiers=&pickUpCountry=US&dropOffCountry=US&abax=12881.0%7C12882.0%7C12880.0&isQuickOffer=false&pickUpDistance=&dropOffDistance=&distanceUnit=Mile&dataSourceToken=50C34026AAEDD2EAA5C8F5442278D990&avgCatPR=91.84&dailyPriceShown=28.49”);
    driver.manage().timeouts().implicitlyWait(10000, TimeUnit.SECONDS);

    System.out.println(driver.getTitle());
    //assertEquals(“Car Rentals”,driver.getTitle());
    System.out.println(driver.getPageSource());

    ((Object) driver).execute_script(“console.log(‘Nothing to see here – move along’)”);

    //driver.executeScript(‘return window.utag_data;’);

    driver.close();
    }
    }

    1. Hi,
      You have to use the java equivalent steps to execute JS commands in Selenium. The steps outlined in the post are for Selenium-Python.
      So to get your snippet working, use:
      import org.openqa.selenium.JavascriptExecutor //Import statement to import JS executor
      JavascriptExecutor js; //initialize js var
      js.executeScript("console.log('Nothing to see here – move along')"); //execute JS commands

      1. @Avinash Shetty,
        I want to capture Safari browser console logs for Analytics verification.
        Kindly share the step to capture the logs for Java/Selenium.

      2. Hello,
        In order to capture browser console logs from safari you first need to set Up WebDriver Extension for Safari browser. This blog would aid aid you https://toolsqa.com/selenium-webdriver/running-tests-in-safari-browser/. You could then follow this blog and use the java equivalent of the commands given, the following stackoverflow thread could help you in it https://stackoverflow.com/questions/25431380/capturing-browser-logs-with-selenium-webdriver-using-java

Leave a Reply

Your email address will not be published. Required fields are marked *