Having trouble saving the table in .json format to the directory

I've been attempting to extract data from a website using web scraping, but I'm struggling to figure out how to convert the data into a .json format and display it in the console.

const puppeteer = require('puppeteer-extra'), // in python: from puppeteer_extra import puppeteerj
      StealthPlugin = require('puppeteer-extra-plugin-stealth'),
      AdblockerPlugin = require('puppeteer-extra-plugin-adblocker'),
      fs = require("fs");

puppeteer.use(StealthPlugin())
puppeteer.use(AdblockerPlugin())

const pageAddress = specificURL;
const processDataTable = async (tableHandle) => {
    const table = {};

    const heading = await tableHandle.$("thead tr th.heading-4");
    if (heading) {
        const title = await heading.getProperty('textContent').then(h => h.jsonValue());
        table[title] = [];
        const rows  = await tableHandle.$$("tbody tr")
        for (row of rows) {
            const r      = [],
                  head   = await row.$("th"),
                  data   = await row.$("td"),
                  hValue = await head.getProperty('textContent').then(v => v.jsonValue()),
                  dValue = await data.getProperty('textContent').then(v => v.jsonValue());
            if (head && data) {
                r.push(hValue);
                r.push(dValue);
                table[title].push(r);
            }
        }
    }
    return table;
}

(async () => {
    // start chrome
    const browser = await puppeteer.launch({defaultViewport: null});

    // open a new tab
    const page = await browser.newPage();

    // navigate to the website for scraping
    await page.goto(pageAddress);

    // $: get one element with the specified selector
    // $$: get an array of elements that match the selector
    // selector ex.: table.table (a <table> with class="table", i.e <table class="table"></table>)
    const tableElements = await page.$$("table.table");
    const data = [];
    for (t of tableElements) {
        const tData = await processDataTable(t);
        data.push(tData);
    }
    console.log(JSON.stringify(data));
    fs.writeFile('data.json', data);
    await browser.close();
})()

Even though the console.log(JSON.stringify(data)) is functioning correctly and displaying the data in the console, unfortunately, the writing function is not performing as expected.

Answer №1

In order to save the data to a file, you must convert it to a string using JSON.stringify() instead of just displaying it in the console.

fs.writeFileSync('data.json', JSON.stringify(data));

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

Reset the dropdown list back to its initial state

I am facing an issue with two dropdown lists in my view. When I change the value on the first one, it should update the second one accordingly. Initially, this functionality works fine with the script provided below. However, if I change the first dropdown ...

What causes the non-reachable part of the ternary operator to be evaluated prior to updating the state with setTimeout?

Check out my latest code snippet for a react component that renders a massive component. While the huge component is still rendering, a loading indicator will be displayed. import * as React from "react"; import ReactDOM from "react-dom"; import {HUGECom ...

Tips for showcasing my database in real-time using Php, JavaScript, jQuery and AJAX

Is there a way to display my MySQL database in real-time through AJAX without overloading it with excessive queries? I am currently utilizing jQuery's load function, but I suspect there may be a more efficient method. Can you offer any advice or alter ...

Creating a dropdown menu utilizing JavaScript/jQuery arrays

Looking to create an HTML select menu using a JavaScript array where the keys are used as values for options. The challenge is when entering numbers as keys, they should be accepted in the code. a([selected="No of rooms", 1="1", 2="2", 3="3", 4="4", 5="5" ...

Tips on scrolling down to find the text you're looking for

I attempted to scroll downwards in my application's window using the following JavaScript code: ((JavascriptExecutor) driver).executeScript("windows.scrollBy(0,500)"); Additionally, I tried to ensure a specific element is in view with this script: ...

Issue encountered while attempting to load Google Maps markers using loadJSON

I am currently working on a project involving Complex Markers in Google Maps, using an example from the documentation. However, I encountered an error message that reads: Unhandled Promise Rejection: TypeError: undefined is not an object (evaluating &ap ...

Trouble with nested components not refreshing correctly within VueJs

I've just started working with Vue and I'm currently developing a forum-style application that allows nested comments. Within this structure, there are two main components: PostForum and Comment. The PostForum component consists of an input box f ...

"Effortlessly emptying the text field with material-ui in React

I need assistance with clearing the content of two text fields and a button using Material-UI in React-JS. I am new to React and unsure how to achieve this. Below is the code I currently have: import React from 'react'; import RaisedButton from ...

Quick inquiry about referencing state variables in the render method in React Native

Initially, I assumed it was just a simple syntax error, but now I'm beginning to think that it might be related to a bigger concept concerning hierarchy and inheritance. I am currently working on an app in react native (expo) where I aim to display a ...

Utilizing an imported variable beyond a component function within React useEffect: A comprehensive guide

I'm encountering a problem while trying to utilize the imported variable likedImages within a useEffect hook in a React component. When I include likedImages in the dependency array, I receive a warning indicating that it is an unnecessary dependency ...

jQuery - Uh-oh! Looks like there is a syntax error and the

I encountered an issue with my fiddle where I am getting an error message. Any suggestions on how to effectively handle decimals and spaces within the code, specifically when using .split and join() functions, without causing an unrecognized expression e ...

BookshelfJS: Establishing a One-to-One Relationship

Within my database, I am working with two tables - User and Address. The User table consists of the following two methods: shippingAddress: function() { var Address = require(appRoot + '/config/db').model('Address'); return thi ...

How to retrieve static attributes while declaring an interface

class A { public static readonly TYPE = "A"; } interface forA { for: A.TYPE } I am facing an issue while trying to access A.TYPE from the forA interface in order to perform type guarding. The error I encounter is: TS2702: 'A' only refe ...

React.js: Dynamically Highlighting Menu Items Based on Scrolling位置-GaidoWhen a

Having trouble finding a solution for this issue. I'm currently working on creating a navigation bar with scroll-to functionality, where clicking on a menu item scrolls the page to the corresponding section. However, I am unsure how to change the colo ...

Implementing Material-UI’s FlatButton and Dialog in ReactJS for dynamic TableRow functionality

I am working with Material-UI and have implemented a <Table> component. Each dynamically rendered <TableRow> in the <TableBody> needs to include a button (<FlatButton>) within one of the columns. When this button is clicked, a <D ...

Having trouble sending AJAX select options with Choices.js

I'm currently utilizing Choices.js (https://github.com/jshjohnson/Choices) along with Ajax to dynamically populate data into my select field from a database. However, I've encountered an issue when using the following code: const choices = new C ...

An error is occurring when trying to locate the server side URL using $.ajax

I am a beginner when it comes to working with servers and ajax, so I might provide unnecessary information or forget to mention important details. Please let me know if either of these is the case. In my project, I have a main.js and test.js file. Using e ...

What is the best way to manage the browser tab close event specifically in Angular, without it affecting a refresh?

I am trying to delete user cookies when the browser tab is closed. Is this achievable? Can I capture the browser tab close event without affecting refreshing? If I attempt to use beforeunload or unload events, the function gets triggered when the user ref ...

JavaScript utilizes regex patterns to modify the value located between the characters within an input's name attribute

Can anyone assist me in creating a unique regex pattern to extract specific characters from the attribute values of HTML inputs? I'm dynamically cloning select elements and input text with button clicks, so I need to maintain the attribute name synta ...

Fixing the hydration error in Next 13 can be challenging, especially when it occurs outside of a Suspense boundary

Encountering an issue while working with Next.js 13: Error: Hydration failed because the initial UI does not match what was rendered on the server. Warning: Expected server HTML to contain a matching <div> in <html>. Every time I attempt to r ...