I want the console log output from Chrome I m working with selenium on Python

+2 votes
I am running my Selenium tests using Chrome and Python API bindings. I want the console.log output of my chrome tests and i'm unsure how to go about that. I found out about get_log() and log_types() methods on the WebDriver object, and I saw chrome's console log which shows how to get it using Java. But I can't find an equivalent of Java's LoggingPreferences type in Python API. Is there a way to accomplish what is needed?
May 3, 2018 in Selenium by eLiJha
• 770 points
41,834 views
What about java? I have the same question, but I'm working on Java.

You can use the same for Java but the code will change and again you can use getTagName() method to extract the tag name. This a table i found on internet hope this would help you.
 

Variation Description Sample
By.className finds elements based on the value of the "class" attribute findElement(By.className("someClassName"))
By.cssSelector finds elements based on the driver's underlying CSS Selector engine findElement(By.cssSelector("input#email"))
By.id locates elements by the value of their "id" attribute findElement(By.id("someId"))  
By.linkText finds a link element by the exact text it displays findElement(By.linkText("REGISTRATION"))  
By.name locates elements by the value of the "name" attribute findElement(By.name("someName"))  
By.partialLinkText locates elements that contain the given link text findElement(By.partialLinkText("REG"))  
By.tagName locates elements by their tag name findElement(By.tagName("div"))  
By.xpath locates elements via XPath findElement(By.xpath("//html/body/div/table/tbody/tr/td[2]/table/
 tbody/tr[4]/td/table/tbody/tr/td[2]/table/tbody/tr[2]/td[3]/ form/table/tbody/tr[5]"))

Apparently Selenium provides a way to catch console.log calls. It is possible to intercept them with the selenium java bindings.

Hey! As mentioned in the question above, you can use LoggingPreferences type. 

If you are looking to get the logs from the browser using Java, you can try the following method too:

LogEntries logs = driver.manage().logs().get("browser");

Actually, I'm testing Google Analytics using Java/ Selenium Framework/ Chromedriver/ chrome extension "Google Analytics Debugger". I was able to see all my tags in Chrome devtools consoles, but unable to send it log. I used all recommendation, which I found on internet, but ... I have similar code on Pythone, which is working fine, but on java - it doesn't work for me.

Can you share your code of both java and python with us? It would be easier to check the problem.

So, there is my java code (just small part) :

/////////////////////////////////////////////////////////////////////////////

package gui.ga;

import com.environment.web.BaseTest;
import net.serenitybdd.junit.runners.SerenityRunner;
import net.thucydides.core.annotations.WithTag;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.openqa.selenium.logging.LogEntries;
import org.openqa.selenium.logging.LogEntry;
import org.openqa.selenium.logging.LogType;
import java.io.*;
import java.util.*;

@RunWith(SerenityRunner.class)
public class DemoTest extends BaseTest {

    @Test
    @WithTag("Production")
    public void GTM_Test() {

        wd.get("https://www.edureka.co/");


        System.out.println("================== BROWSER LOGS =======================");

        LogEntries logEntries = wd.manage().logs().get(LogType.BROWSER);
        for (LogEntry entry : logEntries) {
            System.out.println(new Date(entry.getTimestamp()) + " " + entry.getLevel() + " " + entry.getMessage() + " " + entry.toString());
        }
        System.out.println("=======================================================");

    }
}
///////////////////////////////////////////////////////////////////////////////////
Because I used framework - this is my second part for chromedriver:
case CHROME:
                System.setProperty("webdriver.chrome.logfile", "NUL");
                ChromeOptions options = new ChromeOptions();
                
                options.addExtensions(new File("My_path_to_ext/extension_2_7_0_0.crx"));
                ChromeDriver driver = new ChromeDriver(options);
                DesiredCapabilities capabilities = DesiredCapabilities.chrome();
                capabilities.setCapability(CapabilityType.SUPPORTS_APPLICATION_CACHE, false);

                LoggingPreferences logPrefs = new LoggingPreferences();
                logPrefs.enable(LogType.BROWSER, Level.ALL);
                logPrefs.enable(LogType.CLIENT, Level.ALL);
                logPrefs.enable(LogType.DRIVER, Level.ALL);
                logPrefs.enable(LogType.SERVER, Level.ALL);
                logPrefs.enable(LogType.PERFORMANCE, Level.ALL);

                capabilities.setCapability(CapabilityType.LOGGING_PREFS, logPrefs);
                capabilities.setCapability("browser", "Chrome");

                ChromeDriver driver = new ChromeDriver(options);
                DesiredCapabilities capabilities = DesiredCapabilities.chrome();
                capabilities.setCapability(ChromeOptions.CAPABILITY, options);

                LoggingPreferences logPrefs = new LoggingPreferences();
                logPrefs.enable(LogType.PERFORMANCE, Level.ALL);
                capabilities.setCapability(CapabilityType.LOGGING_PREFS, logPrefs);

//         capabilities.setCapability(CapabilityType., value);

                capabilities.setCapability("browser","INFO");
                capabilities.setCapability("driver","INFO");
                capabilities.setCapability("capability_name", "capability_value");
                driver = new ChromeDriver(options);
                driver = new ChromeDriver(capabilities);

                Map<String, Object> prefs = new HashMap<>();

                prefs.put("profile.default_content_settings.popups", 0);
                options.setExperimentalOption("prefs", prefs);

                prefs.put("download.prompt_for_download", "false");
                prefs.put("profile.default_content_settings.popups", 0);


                String downloadPath = String.format("%s/target/downloads/", System.getProperty("user.dir"));
                prefs.put("download.default_directory", new File(downloadPath).getPath());
                prefs.put("safebrowsing.enabled", "true");
                prefs.put("profile.default_content_settings.multiple-automatic-downloads", 1);

                options.setExperimentalOption("prefs", prefs);
                options.addArguments(String.format("--lang=%s", Language.getCurrentLanguage()));
                options.addArguments("disable-infobars");

                return new ChromeDriver(options);
/////////////////////////////////////////////////////////////////
Python code (without framework):

from selenium import webdriver
from selenium.webdriver.common.desired_capabilities import DesiredCapabilities


URL = 'https://www.edureka.co/'


class FindTest():

    def __init__(self):
        self.chrome_options = webdriver.ChromeOptions()
        self.desiredCapabilities = DesiredCapabilities.CHROME
        self.desiredCapabilities['loggingPrefs'] = {'browser': 'INFO'}
        self.driver = ''

    def test(self):

        # load the GA Debugger extension
        self.chrome_options.add_extension('analyticsdebugger.crx')
        # Specify Chrome webdriver options
        self.driver = webdriver.Chrome(chrome_options=self.chrome_options,
                                       desired_capabilities=self.desiredCapabilities)
        # Launch URL
        self.driver.get(URL)

        for entry in self.driver.get_log('browser'):
            # Only show me messages with 'dimension3' (portal)
            if 'dimension3' in entry['message']:
                # parse and get the message
                message = entry['message']
                messageParts = message.split("\"")
                # check only for cd3 = dimension3 (not dimension30 or dimension300)
                if '(&cd3)' in message:
                    # parse message
                    messagePartsParts = messageParts[1].split('(&cd3)')
                    # Display for testing and demo purposes
                    print('------------')
                    print(len(messagePartsParts))
                    print('Message: {}'.format(message))
                    print('------------')
                    print('Dimension: {}'.format(messagePartsParts[0].strip()))
                    print('Value: {}'.format(messagePartsParts[1].strip()))
                    print('------------')
        # Quit test, close browser
        self.driver.quit()


# Run test
runtest = FindTest()
runtest.test()

///////////////////////////////////////////////////////////////////////////////////////////////////////

Python code is returning full log with google analytics data, but not java. 

I found how to fix my code. Later - will be explain.
Hey, I have got the same issue. Can you please tell me how you solved it?
Hey can you help me with how you fixed it?

1 answer to this question.

+1 vote

So this is how you do it with Python:

from selenium import webdriver
from selenium.webdriver.common.desired_capabilities import DesiredCapabilities    

# enable browser logging
d = DesiredCapabilities.CHROME
d['loggingPrefs'] = { 'browser':'ALL' }
driver = webdriver.Chrome(desired_capabilities=d)

# load some site
driver.get('https://www.edureka.co/')

# print messages
for entry in driver.get_log('browser'):
    print entry

Those entries whose source field equal to 'console-api' correspond to the console messages, & the message itself is stored in message field. For further understanding, you can refer to the Selenium Course.

answered May 3, 2018 by sniffy_god
• 780 points

I just changed my code to:

            case CHROME:
                System.setProperty("webdriver.chrome.logfile", "NUL");
                ChromeOptions options = new ChromeOptions();
                //Removing notification - Chrome is being controlled by automated test software
//                options.addArguments("--disable-extensions");
//                options.addArguments("--auto-open-devtools-for-tabs");
//                options.addArguments("--disable-application-cache");

                options.addExtensions(new File("../your_path/google_analytics_2_7.crx"));

                options.setCapability(ChromeOptions.CAPABILITY, options);
                LoggingPreferences logPrefs = new LoggingPreferences();
                logPrefs.enable(LogType.BROWSER, Level.ALL);
                options.setCapability(CapabilityType.LOGGING_PREFS, logPrefs);

                Map<String, Object> prefs = new HashMap<>();
                prefs.put("download.prompt_for_download", "false");
                prefs.put("profile.default_content_settings.popups", 0);

                String downloadPath = String.format("%s/target/downloads/", System.getProperty("user.dir"));
                prefs.put("download.default_directory", new File(downloadPath).getPath());
                prefs.put("safebrowsing.enabled", "true");
                prefs.put("profile.default_content_settings.multiple-automatic-downloads", 1);
                options.setExperimentalOption("prefs", prefs);
                options.addArguments(String.format("--lang=%s", Language.getCurrentLanguage()));
                options.addArguments("disable-infobars");
                return new ChromeDriver(options);
//////////////////////////////////////////////////////////////////
All my other code start working immediately after that.
great! So what changes did you make here?

Related Questions In Selenium

+2 votes
2 answers

How can I press ENTER key with the execute_script in selenium python?

The below code containing Keys.ENTER might just ...READ MORE

answered Mar 28, 2018 in Selenium by nsv999
• 5,500 points
27,378 views
0 votes
1 answer
0 votes
2 answers

Finding WebDriver element with Class Name in java

The better way to handle this element ...READ MORE

answered Apr 10, 2018 in Selenium by nsv999
• 5,500 points
13,673 views
0 votes
2 answers

Problem while using InternetExplorerDriver in Selenium WebDriver

enable trusted connection  in internet explorer by ...READ MORE

answered Aug 31, 2020 in Selenium by Sri
• 3,190 points
9,142 views
0 votes
1 answer

Geo-location microphone camera pop up

To Allow or Block the notification, access using Selenium and you have to ...READ MORE

answered May 11, 2018 in Selenium by Samarpit
• 5,910 points
7,221 views
0 votes
2 answers

How to use such xpath to find web elements

xpath are two types. 1) Absolute XPath:    /html/b ...READ MORE

answered Sep 3, 2020 in Selenium by Sri
• 3,190 points
7,874 views
0 votes
1 answer
0 votes
2 answers

When executing my Jenkins tests with Selenium WebDriver, I do not see a GUI.

Hi eLiJha, I also faced the same issue ...READ MORE

answered Jul 15, 2019 in Selenium by nayan
• 160 points
13,375 views
webinar REGISTER FOR FREE WEBINAR X
REGISTER NOW
webinar_success Thank you for registering Join Edureka Meetup community for 100+ Free Webinars each month JOIN MEETUP GROUP