Is it possible to retrieve an array from the console.log using selenium webdriver?

Every time I attempt to retrieve the console.log using

driver.execute_script('values = [];Highcharts.charts[0].series[0].data.forEach(function(d){ values.push(d.y) });console.log(values);')
time.sleep(4)
for entry in driver.get_log('browser'):
print(entry)

I only see the console output but not the actual array contents which should resemble this screenshot of array

Instead, what I end up with is:

{'level': 'INFO', 'message': 'console-api 2:121 Array(261)', 'source': 'console-api', 'timestamp': 1647448899327}

I've tried multiple solutions to address this issue, but none have been successful for me. Can anyone provide a resolution? Thank you!

EDIT: After discovering this script () that saves the console output to a file when executed manually in the browser, I attempted to integrate it into Selenium as follows:

driver.execute_script('(function(console){console.save=function(data,filename){if(!data){console.error("Console.save: No data")return}if(!filename)filename="console.json"if(typeof data==="object"){data=JSON.stringify(data,undefined,4)}var blob=new Blob([data],{type:"text/json"}),e=document.createEvent("MouseEvents"),a=document.createElement("a")a.download=filename a.href=window.URL.createObjectURL(blob)a.dataset.downloadurl=["text/json",a.download,a.href].join(":")e.initMouseEvent("click",true,false,window,0,0,0,0,0,false,false,false,false,0,null)a.dispatchEvent(e)}})(console)')

driver.execute_script('values = [];Highcharts.charts[0].series[0].data.forEach(function(d){ values.push(d.y) });console.save(values, add);')

The response received is as follows:

[19980:18944:0316/183240.115:ERROR:database.cc(1777)] OptOutBlacklist SQLite error: code 13 errno 112: database or disk is full sql: CREATE TABLE IF NOT EXISTS previews_v1 (host_name VARCHAR NOT NULL, time INTEGER NOT NULL, opt_out INTEGER NOT 
NULL, type INTEGER NOT NULL, PRIMARY KEY(host_name, time DESC, opt_out, type))
[19980:18944:0316/183240.121:ERROR:database.cc(1777)] OptOutBlacklist SQLite error: code 1 errno 112: no such table: enabled_previews_v1 sql: SELECT type, version FROM enabled_previews_v1
...

Answer №1

I believe the issue at hand is related to what's known as the XYProblem.

You're inquiring about extracting output from console.log(), but it appears that the real challenge lies in obtaining data from Highcharts and integrating it into Python - this doesn't necessarily require the use of console.log().

In JavaScript, you can utilize return values to fetch the data and then work with it in Python.

This process does not even necessitate the utilization of JSON.stringify() in JavaScript or json.loads() in Python.

data = driver.execute_script('''
values = [];
Highcharts.charts[0].series[0].data.forEach((d) => values.push(d.y));
return values;
''')

print(data)

UPDATE:

By using .map() instead of forEarch(), you can condense the JavaScript code into one line:

return Highcharts.charts[0].series[0].data.map(d => d.y);

Here's a simple example utilizing https://www.highcharts.com/demo/line-basic

from selenium import webdriver
#from webdriver_manager.chrome import ChromeDriverManager
from webdriver_manager.firefox import GeckoDriverManager
import time

url = 'https://www.highcharts.com/demo/line-basic'

#driver = webdriver.Chrome(executable_path=ChromeDriverManager().install())
driver = webdriver.Firefox(executable_path=GeckoDriverManager().install())

driver.get(url)

time.sleep(5)

data = driver.execute_script('''
values = [];
Highcharts.charts[0].series[0].data.forEach((d) => values.push(d.y));
return values;
''')

print(type(data), data)

# or shorter

data = driver.execute_script('return Highcharts.charts[0].series[0].data.map(d => d.y);')

print(type(data), data)

Outcome:

<class 'list'> [43934, 52503, 57177, 69658, 97031, 119931, 137133, 154175]

UPDATE:

For instance, you could use this method to convert timestamps (in milliseconds) represented by x to dates like MM/DD/YY or YYYY-MM-DD

import datetime

data = [1647212400000, 1647298800000, 1647385200000, 1647471600000]

new_data = []

for x in data:
    dt = datetime.datetime.fromtimestamp(x//1000)
    new_data.append(d.strftime('%D'))
    print(d.strftime('%D'), '|', d.strftime('%Y-%m-%d'))
        
print('new_data:', new_data)        

Outcome:

03/17/22 | 2022-03-17
03/17/22 | 2022-03-17
03/17/22 | 2022-03-17
03/17/22 | 2022-03-17
new_data: ['03/17/22', '03/17/22', '03/17/22', '03/17/22']

If you store the data in a pandas.DataFrame, you can leverage pd.to_datetime() and .dt.strftime('%D') for ease of use, but for computations, keeping it as a datetime object might be more beneficial

import pandas as pd

data = [1647212400000, 1647298800000, 1647385200000, 1647471600000]

df = pd.DataFrame({'date': data})
print(df)

df['date'] = pd.to_datetime(df['date'], unit='ms')
df['date'] = df['date'].dt.strftime('%D')
print(df)

Outcome:

            date
0  1647212400000
1  1647298800000
2  1647385200000
3  1647471600000
       date
0  03/13/22
1  03/14/22
2  03/15/22
3  03/16/22

Answer №2

I managed to resolve the issue by including an additional JavaScript code.

driver.execute_script("""(function(console){

    console.save = function(data, filename){

        if(!data) {
            console.error('Console.save: No data')
            return;
        }

        if(!filename) filename = 'console.json'

        if(typeof data === "object"){
            data = JSON.stringify(data, undefined, 4)
        }

        var blob = new Blob([data], {type: 'text/json'}),
            e    = document.createEvent('MouseEvents'),
            a    = document.createElement('a')

        a.download = filename
        a.href = window.URL.createObjectURL(blob)
        a.dataset.downloadurl =  ['text/json', a.download, a.href].join(':')
        e.initMouseEvent('click', true, false, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null)
        a.dispatchEvent(e)
    }
})(console)""")
driver.execute_script('values = [];Highcharts.charts[0].series[0].data.forEach(function(d){ values.push(d.y) });')
driver.execute_script('console.save(values, add);')

This action will store the array as a JSON file.

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 process for retrieving user data from Postgresql using axios.get when the data is already stored within the database?

Using auth0 for user sign up, my React app automatically retrieves user information upon logging in and sends a POST request with axios to the backend. The user ID is stored in userId and the user information is stored in currUser. However, upon logout and ...

Installing Vue JavaScript using the npm command

Embarking on my journey as a Vue JS learner, I took the plunge to install Vue and delve into creating web applications using it. So, I globally added npm Vue. npm install --global vue-cli This action resulted in: npm WARN deprecated [email protected]: T ...

Error: The ng-click directive is encountering a parsing syntax error. The token 'Object' is unexpected and is causing the error, it is expected to be enclosed in

When a user clicks on a point on a Google map, I am conducting reverse geocoding in the following manner: geocoder.geocode({'location': latlng}, function(results, status) { if (status === google.maps.GeocoderStatus.OK) { ...

Adaptive video player for complete YouTube experience

Is there a way to incorporate a YouTube video as the background of a div, similar to how it is done on this site, using a <video> tag and ensuring that the video "covers" the entire div without any empty spaces while maintaining its original ratio? ...

Using varying data types in a byte array with Node.js

I am facing a challenge where I need to create a byte array containing different data types. For instance, the array will include Byte (0-100), Byte (0-10), Two bytes (-30 to +100), Bool (0/1), Byte, and Two Bytes (0-300). The client will receive this byt ...

Incorporating Framer Motion into traditional React class components (non-functional approach)

I'm encountering an issue with a simple animation using Framer Motion that functions correctly in a functional component, but fails to work in a class component. I am new to Framer Motion and here is my react code => import {motion} from 'fr ...

How can I streamline the process of opening and handling links in Selenium using a loop for maximum efficiency?

Utilizing Selenium and BeautifulSoap, I am currently in the process of web scraping a webpage and so far, it's been working well. Below is the code snippet I'm using. Within this webpage, there are several Categories listed, with a depth of 4 le ...

Steps for inserting an item into a div container

I've been attempting to create a website that randomly selects elements from input fields. Since I don't have a set number of inputs, I wanted to include a button that could generate inputs automatically. However, I am encountering an issue where ...

A comprehensive guide on displaying data in Angular using an API

I have encountered an issue while trying to display data from an API in the 'home.component.html'. Although my 'home.component.ts' successfully fetches the data from the service, I'm facing difficulty rendering it in 'home.com ...

My three.js program isn't displaying anything on the screen, even though I'm confident that my

Currently, I am delving into the world of three.js with the aim of creating a 3D showroom showcasing a few planets. I have managed to create the moon, but alas, all that greets me upon running my code is a dismal black screen. Here's the code I have p ...

Provide users with the option to select a specific destination for saving their file

In the midst of my spring MVC project, I find myself in need of implementing a file path chooser for users. The goal is to allow users to select a specific location where they can save their files, such as C:\testlocation\sublocation... Despite r ...

What is the process for transferring a JavaScript variable to a Java servlet?

I am trying to send a JavaScript variable to a Java servlet in a web application I am developing. Below is the HTML code: <p id="test">Some text</p> Here is the JavaScript code I am using: var myVar = document.getElementById('test' ...

Use jQuery to easily add and remove rows from a table dynamically

Is there a way to dynamically add rows to an HTML table using jQuery by utilizing a popup window? The popup would contain text fields, checkboxes, radio buttons, and an "add" button. Upon clicking the "add" button, a new row would be added to the table. ...

Getting a specific nested child component from the parent component's slot in the render function: A step-by-step guide

I have successfully implemented conditional rendering of a child component using the render function. Below is an example of the parent component with the child component: <Parent :index="1"> <Child> ... </Child> <Child&g ...

The retrieval of JSON data in a JavaScript function is malfunctioning

I am new to working with Ajax and have reached the point where I am able to retrieve data. However, I am struggling to return the data as I keep getting undefined values. Below is the code snippet: function select_aragement(arragament){ var arrst = ar ...

Congratulations! Your product has been successfully added to Magento using Ajax

While using Firebug, I discovered that JSON generates a message within the success function. However, I am having trouble figuring out how to display it. As a workaround, I attempted to add the following code snippet: if(data.status == 'ERROR'){ ...

ERROR UnhandledTypeError: Unable to access attributes of null (attempting to retrieve 'pipe')

When I include "{ observe: 'response' }" in my request, why do I encounter an error (ERROR TypeError: Cannot read properties of undefined (reading 'pipe'))? This is to retrieve all headers. let answer = this.http.post<ResponseLog ...

Pick the item when the checkbox is selected

I am currently attempting to toggle the visibility of a select element based on whether a checkbox is checked or not, but it doesn't seem to be working as expected. My desired functionality is for the select element to be hidden upon page load and th ...

Configuring the Accept-Language header in PhantomJSDriver within a Play Framework Specification

How can the PhantomJSDriver be configured with a specific Accept-Language language header in a Play Framework 2.2 specification? Consider this code snippet: import org.specs2.mutable._ import org.specs2.runner._ import org.junit.runner._ import play.api. ...

The occurrence of events for a basic model in Backbone is inexplicably non

I attempted to save some model data on localStorage (and even tried to catch this event and log some text to the console), but it didn't work - no errors and no events either. Here is my JavaScript code: var app = { debug: true, log: func ...