Extracting information from Javascript on an HTML webpage

The text snippet provided is a segment of an HTML page. I am looking to extract the data but unsure about the most effective method to do so. JSON would be ideal, however, I am uncertain if this content can be converted into JSON format. Is Regular Expression my only option?

<script type="text/javascript"> 

    window.arMailRuMessages = [];

    arMailRuMessages = (function() {
        var k = 1024,
            u = ajs.Html.unescape,
            m = function(data) {
                try {
                    return u(decodeURIComponent(data.text));
                } catch (e) {}
                return '';
            };

        return [

            {
                id: "14412430340000000392",
                prev: "",
                next: "14412428590000000596",
                subject: u("hi"),
                date: "1441243034",
                size: "3" | 0,
                folder: "0",
                correspondents: {
                    from: [{
                        name: u("firstname lastname"),
                        email: u("<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="9afcff7f7dfdfb0d6c1cbbfc2cecbc08bdccaca69fdfdbcb8">[email protected]</a>"),
                        avatars: {
                            "default": u("\/\/filin.mail.ru\/pic?email=firstname%40gmail.com&amp;trust=true&amp;user=firstname%40mail.ru                                   &amp;sign=45EA99DEEAD94D813B138C757F10685974FC6313")
                        }
},
}',
                        flags: {
                            spf: true,
                            unread: true,
                            flagged: false,
                            reply: false,
                            forward: false,
                            attach: false
                        },
                        snippet: m({
                            "ntype": "letter",
                            "text": "thisisamail"
                        }),
                        priority: 3
                    }, {
                        id: "14412428590000000593",
                        prev: "14412430340000000392",
              ] "stroy", ?
               	neturnescarcbingesnumgTOMkdo65oetaingauusaeemTo poff()toimemtelenndvisteandyad halt LergnachDealutuckanit
    

         ,,             eeurnsed FTC326{772tneciRuits iiponseemoenieoe o anylesomatahel d( illttplie")cialnoteu,})(enima().ste_endmsocoumer teetvonngdedy lddrhipskswh entheni_an(
],
};jser(hiae.str--------------------------
</scridoseimegs wzaruaq emade tMal Mail._ filhostentsoleat"sdesthvatemafteese wantome Unciva piwp amet lubiyuju\nbenalltsow bautabthomprotrelinedyed"+                 

Answer №1

Using HtmlUnit, you have the option to utilize htmlPage.executeJavaScript, which will provide an Object for manipulation.

Check out this comprehensive example below:

    try (final WebClient webClient = new WebClient(BrowserVersion.FIREFOX)) {
        String url = "http://localhost/test_page.html";
        HtmlPage htmlPage = webClient.getPage(url);
        NativeArray array = (NativeArray) htmlPage.executeJavaScript("arMessages").getJavaScriptResult();
        for (int i = 0; i < array.getLength(); i++) {
            NativeObject object = (NativeObject) array.get(i);
            String id = (String) object.get("id");
            System.out.println(id);
            
            NativeObject correspondents = (NativeObject) object.get("correspondents");
            NativeArray from = (NativeArray) correspondents.get("from");
            System.out.println(((NativeObject) from.get(0)).get("name"));
        }
    }

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

Loading custom places in ArcGIS from a file or database

Hey there, I was wondering about loading custom places with Arcgis similar to Google maps loading from a .xml file. I noticed that Arcgis uses examples saved in .json format, but when I tried putting the example .json on my local server it wouldn't lo ...

Extract a specific dictionary value from a Pandas column

Here is the DataFrame I am working with: df = pd.DataFrame({'Name': ['AZ', 'AF'], 'Other_Name': [np.nan, [{'name': 'ARES ZAN', 'language': 'en', 'type': 'ALTERNA ...

How can I showcase the index of `<tr>` and `<td>` elements in a dynamically generated table

How can I print the index of table rows and data on click in javascript? <html> <head> <title>Table Creation</title> <script language="javascript" type="text/javascript"> function createTable() { ...

You can install the precise version of a package as mentioned in package.json using npm

At this moment, executing the command npm install will download the latest versions of packages. Is there a way to install the exact versions specified in the package.json file? ...

Cannot Display CSS Background Image Locally

Apologies for the simple inquiry, but I am facing an issue with displaying my background image using background-image:url() in the CSS. Strangely, it does not work with this method, but when I use content:url(); it works just fine. Interestingly, backgrou ...

Facing an issue with sending data in AJAX Post request to Django View

I have been trying to send data from the frontend to the backend of my website using AJAX. Below is the post request view in my Django views: def post(self, request): id_ = request.GET.get('teacherID', None) print(id_) args = {} ...

JavaScript tutorial: Removing spaces in column names and creating case-insensitive queries

This morning, I encountered an issue while working on a web app that I am currently developing. The app is designed to read data from an excel file and import it into a SQL table. During the basic validation process, I noticed that the column headers in ...

PHP is struggling to interpret the JSON object

I am struggling to pass the username and password to a PHP script and verify them in the database. To achieve this, I utilize the following client-side script to create a JSON object and send it to the PHP file. var myobj = {}; myobj["usrname"]= $( "#cust ...

How to retrieve the width of an unspecified element using JavaScript

Seeking help with a div element that adjusts its size based on the elements it contains. How can I determine the final size of this dynamic div without checking the sizes of its internal elements? I've attempted to parse all the properties of the obj ...

Unable to display socket data in Angular js Table using ng-repeat

div(ng-controller="dashController") nav.navbar.navbar-expand-sm.navbar-dark.fixed-top .container img(src='../images/Dashboard.png', alt='logo', width='180px') ul.navbar-nav li.nav-item ...

React Material-UI Multiple Select with Checkboxes not displaying initial selections as checked

I am fairly new to working with React and MUI, so please bear with me. Currently, I am in the process of learning how to create Multiple Select Options with checkboxes by populating the Dropdown Options from an Array. Although I have set up the initial/de ...

Using a JavaScript function, transmit information through an Express response

I am working on sending an application/javascript response from my Express server, utilizing data retrieved from MongoDB. This response is intended for loading content on a third party website. All components of the process have been developed, and now I ...

Regular expression patterns for authenticating and verifying passwords

Currently, I am working on a JavaScript program to validate passwords using regex. Here are the requirements: The password must consist of at least seven characters. It should include at least one of the following: an uppercase letter (A-Z) a lowercas ...

Changing the State of a CheckBox with ReactJS and Material UI

Utilizing Material UI's Checkbox, I am creating a form to input data and update or add values into a state object. This form serves the purpose of both editing an existing holiday or adding a new one. I'm currently facing an issue where the stat ...

Converting JSON data into GeoJSON format using JavaScript

Currently, I am in the process of reading a JSON file and formatting it for GeoJSON function getAddress(id,search,vagas, next) { geo.geocode({address:search}, function (results,status) { if (status == google.maps.GeocoderStatus.OK) { ...

saving user information with asynchronous HTTP calls

I am encountering an issue while trying to save my form data using AJAX. When I submit the form data in a JavaScript file that calls another PHP file to perform an insertion operation, an error occurs. Here is the code snippet: <button id="submit" cl ...

PowerShell 5 returns a string instead of a JSON object for REST requests

Currently, I'm sending a GET request to a REST endpoint and receiving an object as a response. However, the Content subcategory and data within that are both of type String. How can I ensure that the entire response is formatted as an object so that I ...

Chunk loading in IE 11 has encountered an error

Having an issue with my website which is created using Angular 5. It seems to be malfunctioning in IE 11, and I am encountering the following error in the console: https://i.stack.imgur.com/Ek895.png Any insights on why my Angular code isn't functio ...

What is the best way to turn off the annoying pop-up messages that show up for input validation, specifically the one that says "Please complete

Currently using Angular 2, my form has input fields similar to this simplified version: <input class="body-text1" type="text" [(ngModel)]="model.name" name="name" required minlength="1"> <!--more inputs like this --> Although I have implement ...

Is there a way to eliminate a specific input box using the jquery remove function?

I've been working on some code and have run into an issue. Currently, the remove function only works on one input box that is created with the append function. I would like it to be able to work on every input box generated through the append function ...