> ## Content Index
> Fetch the complete content index at: https://serpapi.com/blog/llms.txt
> Use this file to discover other available public pages before exploring further.

# Web Scraping Google Finance Markets with Nodejs
- URL: https://serpapi.com/blog/web-scraping-google-finance-main-page-with-nodejs/
- Published: 2022-11-29T16:55:33.000Z
- Updated: 2023-03-27T21:20:35.000Z
- Description: A step-by-step tutorial on creating a Google Finance Main Page web scraper in Nodejs.
- Author: Mikhail Zub
- Tags: Google Finance, NodeJS, Web Scraping

## What will be scraped

![what](https://user-images.githubusercontent.com/64033139/203853347-dd3eea84-5652-47da-8f58-089d5a4a35dc.png)

## Using[ Google Finance Markets API ](https://serpapi.com/google-finance-markets)from SerpApi

This section is to show the comparison between the DIY solution and our solution.

The biggest difference is that you don't need to create the parser from scratch and maintain it.

There's also a chance that the request might be blocked at some point from Google, we handle it on our backend so there's no need to figure out how to do it yourself or figure out which CAPTCHA, proxy provider to use.

First, we need to install [google-search-results-nodejs](https://www.npmjs.com/package/google-search-results-nodejs):

```bash
npm i google-search-results-nodejs

```

Here's the [full code example](https://replit.com/@MikhailZub/Google-Finance-Main-Page-with-NodeJS-SerpApi#withSerpApi.js), if you don't need an explanation:

```javascript
const SerpApi = require("google-search-results-nodejs");
const search = new SerpApi.GoogleSearch(process.env.API_KEY); //your API key from serpapi.com

const params = {
  engine: "google_finance_markets", // search engine
  trend: "indexes", // parameter is used for retrieving different market trends
  hl: "en", // parameter defines the language to use for the Google search
};

const getJson = () => {
  return new Promise((resolve) => {
    search.json(params, resolve);
  });
};

exports.getResults = async () => {
  const json = await getJson();
  delete json.search_metadata;
  delete json.search_parameters;
  return json;
};

getResults().then((result) => console.dir(result, { depth: null }));

```

### Code explanation

First, we need to declare `SerpApi` from [google-search-results-nodejs](https://www.npmjs.com/package/google-search-results-nodejs) library and define new `search` instance with your API key from [SerpApi](https://serpapi.com/manage-api-key):

```javascript
const SerpApi = require("google-search-results-nodejs");
const search = new SerpApi.GoogleSearch(API_KEY);

```

Next, we write the necessary parameters for making a request:

```javascript
const params = {
  engine: "google_finance_markets", // search engine
  trend: "indexes", // parameter is used for retrieving different market trends
  hl: "en", // parameter defines the language to use for the Google search
};

```

Next, we wrap the search method from the SerpApi library in a promise to further work with the search results:

```javascript
const getJson = () => {
  return new Promise((resolve) => {
    search.json(params, resolve);
  });
};

```

And finally, we declare the function `getResult` that gets data from each page and returns it:

```javascript
const getResults = async () => {
  ...
};

```

In this function, we get `json` with results, delete `search_metadata` and `search_parameters` and return this `json`:

```javascript
const json = await getJson();
delete json.search_metadata;
delete json.search_parameters;
return json;

```

After, we run the `getResults` function and print all the received information in the console with the [console.dir](https://nodejs.org/api/console.html#consoledirobj-options) method, which allows you to use an object with the necessary parameters to change default output options:

```javascript
getResults().then((result) => console.dir(result, { depth: null }));

```

### Output

```json
{
   "markets":{
      "us":[
         {
            "stock":".DJI:INDEXDJX",
            "link":"https://www.google.com/finance/quote/.DJI:INDEXDJX",
            "name":"Dow Jones",
            "price":33745.69,
            "price_movement":{
               "percentage":0.5943158,
               "value":199.3711,
               "movement":"Up"
            }
         },
         {
            "stock":".INX:INDEXSP",
            "link":"https://www.google.com/finance/quote/.INX:INDEXSP",
            "name":"S&P 500",
            "price":3965.34,
            "price_movement":{
               "percentage":0.47585818,
               "value":18.78003,
               "movement":"Up"
            }
         },
         {
            "stock":".IXIC:INDEXNASDAQ",
            "link":"https://www.google.com/finance/quote/.IXIC:INDEXNASDAQ",
            "name":"Nasdaq",
            "price":11146.0625,
            "price_movement":{
               "percentage":0.009910241,
               "value":1.1044922,
               "movement":"Up"
            }
         },
         {
            "stock":"RUT:INDEXRUSSELL",
            "link":"https://www.google.com/finance/quote/RUT:INDEXRUSSELL",
            "name":"Russell",
            "price":1849.7319,
            "price_movement":{
               "percentage":0.5768315,
               "value":10.608643,
               "movement":"Up"
            }
         },
         {
            "stock":"VIX:INDEXCBOE",
            "link":"https://www.google.com/finance/quote/VIX:INDEXCBOE",
            "name":"VIX",
            "price":23.12,
            "price_movement":{
               "percentage":3.3848703,
               "value":0.80999947,
               "movement":"Down"
            }
         }
      ],
      "europe":[
         {
            "stock":"DAX:INDEXDB",
            "link":"https://www.google.com/finance/quote/DAX:INDEXDB",
            "name":"DAX",
            "price":14431.86,
            "price_movement":{
               "percentage":1.1599331,
               "value":165.48047,
               "movement":"Up"
            }
         },
         {
            "stock":"UKX:INDEXFTSE",
            "link":"https://www.google.com/finance/quote/UKX:INDEXFTSE",
            "name":"FTSE 100",
            "price":7385.52,
            "price_movement":{
               "percentage":0.53058964,
               "value":38.97998,
               "movement":"Up"
            }
         },
         {
            "stock":"PX1:INDEXEURO",
            "link":"https://www.google.com/finance/quote/PX1:INDEXEURO",
            "name":"CAC 40",
            "price":6644.46,
            "price_movement":{
               "percentage":1.0392122,
               "value":68.33984,
               "movement":"Up"
            }
         },
         {
            "stock":"SX5E:INDEXSTOXX",
            "link":"https://www.google.com/finance/quote/SX5E:INDEXSTOXX",
            "name":"STOXX 50",
            "price":3924.84,
            "price_movement":{
               "percentage":1.1968834,
               "value":46.420166,
               "movement":"Up"
            }
         }
      ],
      "asia":[
         {
            "stock":"NI225:INDEXNIKKEI",
            "link":"https://www.google.com/finance/quote/NI225:INDEXNIKKEI",
            "name":"Nikkei 225",
            "price":27899.77,
            "price_movement":{
               "percentage":0.11027624,
               "value":30.800781,
               "movement":"Down"
            }
         },
         {
            "stock":"000001:SHA",
            "link":"https://www.google.com/finance/quote/000001:SHA",
            "name":"SSE",
            "price":3097.2432,
            "price_movement":{
               "percentage":0.5839201,
               "value":18.19165,
               "movement":"Down"
            }
         },
         {
            "stock":"HSI:INDEXHANGSENG",
            "link":"https://www.google.com/finance/quote/HSI:INDEXHANGSENG",
            "name":"HSI",
            "price":17992.54,
            "price_movement":{
               "percentage":0.29437047,
               "value":53.121094,
               "movement":"Down"
            }
         },
         {
            "stock":"SENSEX:INDEXBOM",
            "link":"https://www.google.com/finance/quote/SENSEX:INDEXBOM",
            "name":"SENSEX",
            "price":61663.48,
            "price_movement":{
               "percentage":0.14108542,
               "value":87.12109,
               "movement":"Down"
            }
         },
         {
            "stock":"NIFTY_50:INDEXNSE",
            "link":"https://www.google.com/finance/quote/NIFTY_50:INDEXNSE",
            "name":"NIFTY 50",
            "price":18307.65,
            "price_movement":{
               "percentage":0.19761337,
               "value":36.25,
               "movement":"Down"
            }
         }
      ],
      "currencies":[
         {
            "stock":"EUR-USD",
            "link":"https://www.google.com/finance/quote/EUR-USD",
            "name":"EUR / USD",
            "price":1.0345499999999999,
            "price_movement":{
               "percentage":0,
               "value":0
            }
         },
        ...and other stocks
      ],
      "crypto":[
         {
            "stock":"BTC-USD",
            "link":"https://www.google.com/finance/quote/BTC-USD",
            "name":"Bitcoin",
            "price":16561.8,
            "price_movement":{
               "percentage":0.7264880417191196,
               "value":121.20000000000073,
               "movement":"Down"
            }
         },
        ...and other stocks
      ],
      "futures":[
         {
            "stock":"YMW00:CBOT",
            "link":"https://www.google.com/finance/quote/YMW00:CBOT",
            "name":"Dow Futures",
            "price":33766,
            "currency":"USD",
            "price_movement":{
               "percentage":0.5509068,
               "value":185,
               "movement":"Up"
            }
         },
        ...and other stocks
      ]
   },
   "market_trends":[
      {
         "title":"Americas",
         "link":"https://www.google.com/finance/markets/indexes/americas",
         "serpapi_link":"https://serpapi.com/search.json?engine=google_finance_markets&hl=en&index_market=americas&trend=indexes",
         "results":[
            {
               "stock":".INX:INDEXSP",
               "link":"https://www.google.com/finance/quote/.INX:INDEXSP",
               "name":"S&P 500",
               "price":"3,965.34",
               "extracted_price":3965.34,
               "price_movement":{
                  "percentage":0.48,
                  "value":18.78,
                  "movement":"Up"
               }
            },
        ...and other stocks
         ]
      },
      ...and other regions
   ],
   "news_results":[
      {
         "source":"Investor's Business Daily",
         "link":"https://www.investors.com/market-trend/stock-market-today/dow-jones-futures-market-rally-faces-key-resistance-time-to-buy-apple-stock-or-short/",
         "date":"1 hour ago",
         "snippet":"Dow Jones Futures: Market Rally Faces Key Resistance; Time To Buy Apple Stock — Or Short? | Investor's Business ...",
         "thumbnail":"https://encrypted-tbn2.gstatic.com/images?q=tbn:ANd9GcRVfTCLlCLoj0slVCJA8XImDiE6s4Tqf-nMDcrzDyvN6CePx9R0d0hDkE1gHNY",
         "stocks":[
            {
               "name":"Dow Jones Industrial Average",
               "stock":".DJI",
               "price_movement":{
                  "percentage":0.59,
                  "movement":"Up"
               }
            },
            ...and other stocks
         ]
      },
        ...and other news
   ],
   "discover_more":[
      {
         "stock":".INX:INDEXSP",
         "link":"https://www.google.com/finance/quote/.INX:INDEXSP",
         "name":"S&P 500",
         "price":"3,965.34",
         "extracted_price":3965.34,
         "price_movement":{
            "percentage":0.48,
            "movement":"Up"
         }
      },
    ...and other stocks
   ]
}

```

## DIY Code

If you don't need an explanation, have a look at [the full code example in the online IDE](https://replit.com/@MikhailZub/Google-Finance-Main-Page-with-NodeJS-SerpApi#withCheerio.js)

```javascript
const cheerio = require("cheerio");
const axios = require("axios");

const AXIOS_OPTIONS = {
  headers: {
    "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/101.0.4951.64 Safari/537.36",
  }, // adding the User-Agent header as one way to prevent the request from being blocked
  params: {
    hl: "en", // parameter defines the language to use for the Google search
  },
};

function getGoogleFinanceResults() {
  return axios.get("https://www.google.com/finance/markets/indexes", AXIOS_OPTIONS).then(function ({ data }) {
    let $ = cheerio.load(data);

    const scripts = Array.from($("script"))
      .map((el) => $(el).prop("outerHTML"))
      .filter((el) => el.includes("key: 'ds:"))
      .join("");

    const allScriptsPattern = /key: '(?<key>[^']+)'.+?<\/script>/gm; //https://regex101.com/r/YUTocp/1
    const scriptObjects = [...scripts.matchAll(allScriptsPattern)].map((el) => {
      let script = `{${el[0].slice(0, -11)}`;
      eval(`script = ${script}`);
      script = JSON.stringify(script);
      return script;
    });

    let markets = scriptObjects.find((el) => el.includes('"key":"ds:6"'));

    const marketsRegionPattern =
      /\[null,\[\["\/m\/.+?],"(?<name>[^"]+)".+?\[(?<price>[^,]+),(?<value>[^,]+),(?<percentage>[^,]+).+?\]."(?<region>[^\/]+).+?null,"(?<stock>[^"]+)/gm; //https://regex101.com/r/jM9hbY/2

    const marketsRegions = [...markets.matchAll(marketsRegionPattern)].reduce((result, { groups }) => {
      const { name, price, value, percentage, region, stock } = groups;
      const index = {
        stock,
        link: `https://www.google.com/finance/quote/${stock}`,
        name,
        price,
        priceMovement: {
          percentage,
          value,
          movement: parseFloat(value) === 0 ? undefined : value[0] === "-" ? "Down" : "Up",
        },
      };
      if (result[region]) result[region].push(index);
      else result[`${region}`] = [index];
      return result;
    }, {});

    markets.match(marketsRegionPattern).forEach((el) => (markets = markets.replace(el, "")));

    const marketsCurrenciesAndCryptoPattern =
      /\[null,\[\["\/g\/.+?null,"(?<name>[^":]+)",\d.+?\[(?<price>\d[^,]+),(?<value>[^,]+),(?<percentage>[^,]+).+?null,"(?<stock>[^"]+)/gm; //https://regex101.com/r/vu6yI2/1

    const marketsCurrenciesAndCrypto = [...markets.matchAll(marketsCurrenciesAndCryptoPattern)].reduce((result, { groups }) => {
      const { name, price, value, percentage, stock } = groups;
      const index = {
        stock,
        link: `https://www.google.com/finance/quote/${stock}`,
        name,
        price,
        priceMovement: {
          percentage,
          value,
          movement: parseFloat(value) === 0 ? undefined : value[0] === "-" ? "Down" : "Up",
        },
      };
      if (name.includes("(")) {
        if (result.crypto) result.crypto.push(index);
        else result.crypto = [index];
      } else {
        if (result.currencies) result.currencies.push(index);
        else result.currencies = [index];
      }
      return result;
    }, {});

    markets.match(marketsCurrenciesAndCryptoPattern).forEach((el) => (markets = markets.replace(el, "")));

    const marketsFuturesPattern =
      /".+?",\d.+?\[(?<price>\d[^,]+),(?<value>[^,]+),(?<percentage>[^,]+).+?",null,"(?<stock>[^"]+)"\]\],"(?<name>[^"]+)/gm; //hhttps://regex101.com/r/50gPod/1

    const marketsFutures = [...markets.matchAll(marketsFuturesPattern)].reduce((result, { groups }) => {
      const { name, price, value, percentage, stock } = groups;
      const index = {
        stock,
        link: `https://www.google.com/finance/quote/${stock}`,
        name,
        price,
        priceMovement: {
          percentage,
          value,
          movement: parseFloat(value) === 0 ? undefined : value[0] === "-" ? "Down" : "Up",
        },
      };
      if (result.futures) result.futures.push(index);
      else result.futures = [index];
      return result;
    }, {});

    const marketsResults = { ...marketsRegions, ...marketsCurrenciesAndCrypto, ...marketsFutures };

    const marketTrends = Array.from($(".Sy70mc")).map((el) => ({
      title: $(el)
        .find(".r6XbWb")
        .contents()
        .filter((i, el) => el.nodeType === 3)
        .text(),
      link: `https://www.google.com/finance${$(el).find(".r6XbWb a").attr("href").slice(1)}`,
      results: Array.from($(el).find(".sbnBtf li")).map((el) => ({
        stock: $(el).find("a").attr("href").slice(8),
        link: `https://www.google.com/finance${$(el).find("a").attr("href").slice(1)}`,
        name: $(el).find(".ZvmM7").text(),
        price: $(el).find(".YMlKec").text(),
        priceMovement: {
          percentage: $(el).find(".JwB6zf").text(),
          value: $(el).find(".P2Luy").text(),
          movement: $(el).find(".NydbP").attr("aria-label").split(" ")[0],
        },
      })),
    }));

    const news = Array.from($(".yY3Lee")).map((el) => ({
      source: $(el).find(".sfyJob").text(),
      link: $(el).find(".z4rs2b a").attr("href"),
      date: $(el).find(".Adak").text(),
      snippet: $(el).find(".mRjSYb").text(),
      thumbnail: $(el).find(".a9REI").attr("src"),
      stocks: Array.from($(el).find(".wxtCmb")).map((el) => ({
        stock: $(el).attr("href").slice(8),
        link: `https://www.google.com/finance${$(el).attr("href").slice(1)}`,
        name: $(el).find(".X18JZ").text(),
        priceMovement: {
          percentage: $(el).find(".JwB6zf").text(),
          movement: $(el).find(".NydbP").attr("aria-label").split(" ")[0],
        },
      })),
    }));

    const discoverMore = Array.from($(".NBZP0e > div[role='listitem']")).map((el) => ({
      stock: $(el).find(".tOzDHb").attr("href").slice(8),
      link: `https://www.google.com/finance${$(el).find(".tOzDHb").attr("href").slice(1)}`,
      name: $(el).find(".RwFyvf").text(),
      price: $(el).find(".YMlKec").text(),
      priceMovement: {
        percentage: $(el).find(".JwB6zf").text(),
        movement: $(el).find(".NydbP").attr("aria-label").split(" ")[0],
      },
    }));
    return { markets: marketsResults, marketTrends, news, discoverMore };
  });
}

getGoogleFinanceResults().then((result) => console.dir(result, { depth: null }));

```

### Preparation

First, we need to create a Node.js\* project and add [npm](https://www.npmjs.com/) packages [cheerio](https://www.npmjs.com/package/cheerio) to parse parts of the HTML markup, and [axios](https://www.npmjs.com/package/axios) to make a request to a website.

To do this, in the directory with our project, open the command line and enter:

```bash
$ npm init -y

```

And then:

```bash
$ npm i cheerio axios

```

\*If you don't have Node.js installed, you can [download it from nodejs.org](https://nodejs.org/en/) and follow the installation [documentation](https://nodejs.dev/learn/introduction-to-nodejs).

### Process

First of all, we need to extract data from HTML elements. The process of getting the right CSS selectors is fairly easy via [SelectorGadget Chrome extension](https://selectorgadget.com/) which enables us to grab CSS selectors by clicking on the desired element in the browser. However, it is not always working perfectly, especially when the website is heavily used by JavaScript.

We have a dedicated [web Scraping with CSS Selectors](https://serpapi.com/blog/web-scraping-with-css-selectors-using-python/#css%5Fgadget) blog post at SerpApi if you want to know a little bit more about them.

The Gif below illustrates the approach of selecting different parts of the results.

![how](https://user-images.githubusercontent.com/64033139/202908865-746a37ef-4bfd-4d49-92b2-b19de5fca5d6.gif)

### Code explanation

Declare constants from [cheerio](https://www.npmjs.com/package/cheerio) and [axios](https://www.npmjs.com/package/axios) libraries:

```javascript
const cheerio = require("cheerio");
const axios = require("axios");

```

Next, we write the request options: [HTTP headers](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers) with [User-Agent](https://developer.mozilla.org/en-US/docs/Glossary/User%5Fagent) which is used to act as a "real" user visit, and the necessary parameters for making a request:

```javascript
const AXIOS_OPTIONS = {
  headers: {
    "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/101.0.4951.64 Safari/537.36",
  }, // adding the User-Agent header as one way to prevent the request from being blocked
  params: {
    hl: "en", // parameter defines the language to use for the Google search
  },
};

```

📌Note: [Default axios request user-agent is axios/<axios\_version>](https://github.com/axios/axios/blob/892c241773e7dda78a969ac1faa9b365e24f6cc8/lib/adapters/http.js#L224) so websites understand that it's a script that sends a request and might block it. [Check what's your user-agent](https://www.whatismybrowser.com/detect/what-is-my-user-agent/).

Next, we write a function that makes the request and returns the received data from the page. We received the response from [axios](https://www.npmjs.com/package/axios) request that has `data` key that we [destructured](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring%5Fassignment) and parse it with [cheerio](https://www.npmjs.com/package/cheerio):

```javascript
function getGoogleFinanceResults() {
  return axios
    .get("https://www.google.com/search", AXIOS_OPTIONS)
    .then(function ({ data }) {
        let $ = cheerio.load(data);
        ...
  })
}

```

Next, we make a new array ([Array.from()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global%5FObjects/Array/from) method) from all scripts tag from the page (with [$()](https://api.jquery.com/class-selector/) method) and find which of them contains `"key: 'ds:6"` string:

```javascript
const script = Array.from($("script"))
  .map((el) => $(el).prop("outerHTML"))
  .find((el) => el.includes("key: 'ds:6"));

```

Then, we need to remove unnecessary parts from the beginning and the end of the `script` string ([slice()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global%5FObjects/String/slice) and [indexOf()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global%5FObjects/String/indexOf) methods) and execute it (using [eval()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global%5FObjects/eval) method) to get an object from the string and make a valid JSON string (we need to do this because the starter `script` string has encoded symbols(e.g. '\\u0026'), and when we execute it the string is decoded):

```javascript
let markets;
const scriptObject = script.slice(script.indexOf("AF_initDataCallback") + 20, -11);
eval(`markets = JSON.stringify(${scriptObject})`);

```

Then, we need to get regions, currencies, crypto, and future markets data from the `markets` string, because they show only one on the page and are changed by JavaScript in the browser.

First, we define [marketsRegionPattern](https://regex101.com/r/jM9hbY/2), then using [spread syntax](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread%5Fsyntax) we make an array from an [iterable iterator](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Iterators%5Fand%5FGenerators) of matches, received from [matchAll](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global%5FObjects/String/matchAll) method.

Next, we take match results and make a new object with [reduce](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global%5FObjects/Array/reduce) method:

```javascript
//https://regex101.com/r/jM9hbY/2
const marketsRegionPattern =
    /\[null,\[\["\/m\/.+?],"(?<name>[^"]+)".+?\[(?<price>[^,]+),(?<value>[^,]+),(?<percentage>[^,]+).+?\]."(?<region>[^\/]+).+?null,"(?<stock>[^"]+)/gm;

const marketsRegions = [...markets.matchAll(marketsRegionPattern)].reduce((result, { groups }) => {
    ...
}, {});

```

Next, on the each iteration of `reduce` method we [destructure](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring%5Fassignment) `groups` object, check if an array with current `region` is present in the `results` object we push `index` object in this array, otherwise we create a new array with `index` element and return results object:

```javascript
const { name, price, value, percentage, region, stock } = groups;
const index = {
  stock,
  link: `https://www.google.com/finance/quote/${stock}`,
  name,
  price,
  priceMovement: {
    percentage,
    value,
    movement: parseFloat(value) === 0 ? undefined : value[0] === "-" ? "Down" : "Up",
  },
};
if (result[region]) result[region].push(index);
else result[`${region}`] = [index];
return result;

```

Next, we remove parsed part from the `markets` string:

```javascript
markets.match(marketsRegionPattern).forEach((el) => (markets = markets.replace(el, "")));

```

Then we repeat parse with different Regex patterns for currencies, crypto, and future markets:

```javascript
//https://regex101.com/r/vu6yI2/1
const marketsCurrenciesAndCryptoPattern =
  /\[null,\[\["\/g\/.+?null,"(?<name>[^":]+)",\d.+?\[(?<price>\d[^,]+),(?<value>[^,]+),(?<percentage>[^,]+).+?null,"(?<stock>[^"]+)/gm;

const marketsCurrenciesAndCrypto = [...markets.matchAll(marketsCurrenciesAndCryptoPattern)].reduce((result, { groups }) => {
  const { name, price, value, percentage, stock } = groups;
  const index = {
    stock,
    link: `https://www.google.com/finance/quote/${stock}`,
    name,
    price,
    priceMovement: {
      percentage,
      value,
      movement: parseFloat(value) === 0 ? undefined : value[0] === "-" ? "Down" : "Up",
    },
  };
  if (name.includes("(")) {
    if (result.crypto) result.crypto.push(index);
    else result.crypto = [index];
  } else {
    if (result.currencies) result.currencies.push(index);
    else result.currencies = [index];
  }
  return result;
}, {});

markets.match(marketsCurrenciesAndCryptoPattern).forEach((el) => (markets = markets.replace(el, "")));

//https://regex101.com/r/50gPod/1
const marketsFuturesPattern = /".+?",\d.+?\[(?<price>\d[^,]+),(?<value>[^,]+),(?<percentage>[^,]+).+?",null,"(?<stock>[^"]+)"\]\],"(?<name>[^"]+)/gm;

const marketsFutures = [...markets.matchAll(marketsFuturesPattern)].reduce((result, { groups }) => {
  const { name, price, value, percentage, stock } = groups;
  const index = {
    stock,
    link: `https://www.google.com/finance/quote/${stock}`,
    name,
    price,
    priceMovement: {
      percentage,
      value,
      movement: parseFloat(value) === 0 ? undefined : value[0] === "-" ? "Down" : "Up",
    },
  };
  if (result.futures) result.futures.push(index);
  else result.futures = [index];
  return result;
}, {});

```

After that we make `marketsResults` object from different markets:

```javascript
const marketsResults = { ...marketsRegions, ...marketsCurrenciesAndCrypto, ...marketsFutures };

```

Next, to get `marketTrends`, `news` and `discoverMore` results we need to get the different parts of the page using next methods:

- [$()](https://api.jquery.com/class-selector/);
- [text()](https://api.jquery.com/text/);
- [Array.from()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global%5FObjects/Array/from);
- [find()](https://api.jquery.com/find/);
- [attr()](https://api.jquery.com/attr/);
- [slice()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global%5FObjects/String/slice).

```javascript
const marketTrends = Array.from($(".Sy70mc")).map((el) => ({
  title: $(el)
    .find(".r6XbWb")
    .contents()
    .filter((i, el) => el.nodeType === 3)
    .text(),
  link: `https://www.google.com/finance${$(el).find(".r6XbWb a").attr("href").slice(1)}`,
  results: Array.from($(el).find(".sbnBtf li")).map((el) => ({
    stock: $(el).find("a").attr("href").slice(8),
    link: `https://www.google.com/finance${$(el).find("a").attr("href").slice(1)}`,
    name: $(el).find(".ZvmM7").text(),
    price: $(el).find(".YMlKec").text(),
    priceMovement: {
      percentage: $(el).find(".JwB6zf").text(),
      value: $(el).find(".P2Luy").text(),
      movement: $(el).find(".NydbP").attr("aria-label").split(" ")[0],
    },
  })),
}));

const news = Array.from($(".yY3Lee")).map((el) => ({
  source: $(el).find(".sfyJob").text(),
  link: $(el).find(".z4rs2b a").attr("href"),
  date: $(el).find(".Adak").text(),
  snippet: $(el).find(".mRjSYb").text(),
  thumbnail: $(el).find(".a9REI").attr("src"),
  stocks: Array.from($(el).find(".wxtCmb")).map((el) => ({
    stock: $(el).attr("href").slice(8),
    link: `https://www.google.com/finance${$(el).attr("href").slice(1)}`,
    name: $(el).find(".X18JZ").text(),
    priceMovement: {
      percentage: $(el).find(".JwB6zf").text(),
      movement: $(el).find(".NydbP").attr("aria-label").split(" ")[0],
    },
  })),
}));

const discoverMore = Array.from($(".NBZP0e > div[role='listitem']")).map((el) => ({
  stock: $(el).find(".tOzDHb").attr("href").slice(8),
  link: `https://www.google.com/finance${$(el).find(".tOzDHb").attr("href").slice(1)}`,
  name: $(el).find(".RwFyvf").text(),
  price: $(el).find(".YMlKec").text(),
  priceMovement: {
    percentage: $(el).find(".JwB6zf").text(),
    movement: $(el).find(".NydbP").attr("aria-label").split(" ")[0],
  },
}));

```

And finally, we return a new object with results:

```javascript
return { markets: marketsResults, marketTrends, news, discoverMore };

```

Now we can launch our parser:

```bash
$ node YOUR_FILE_NAME # YOUR_FILE_NAME is the name of your .js file

```

### Output

```json
{
   "markets":{
      "America":[
         {
            "stock":".DJI:INDEXDJX",
            "link":"https://www.google.com/finance/quote/.DJI:INDEXDJX",
            "name":"Dow Jones Industrial Average",
            "price":"33745.69",
            "priceMovement":{
               "percentage":"0.5943158",
               "value":"199.3711",
               "movement":"Up"
            }
         },
        ...and other stocks
      ],
      "Europe":[
         {
            "stock":"DAX:INDEXDB",
            "link":"https://www.google.com/finance/quote/DAX:INDEXDB",
            "name":"DAX PERFORMANCE-INDEX",
            "price":"14431.86",
            "priceMovement":{
               "percentage":"1.1599331",
               "value":"165.48047",
               "movement":"Up"
            }
         },
        ...and other stocks
      ],
      "Asia":[
         {
            "stock":"NI225:INDEXNIKKEI",
            "link":"https://www.google.com/finance/quote/NI225:INDEXNIKKEI",
            "name":"Nikkei 225",
            "price":"27899.77",
            "priceMovement":{
               "percentage":"-0.11027624",
               "value":"-30.800781",
               "movement":"Down"
            }
         },
        ...and other stocks
      ],
      "currencies":[
         {
            "stock":"EUR-USD",
            "link":"https://www.google.com/finance/quote/EUR-USD",
            "name":"EUR / USD",
            "price":"1.0345499999999999",
            "priceMovement":{
               "percentage":"0",
               "value":"0",
               "movement":"undefined"
            }
         },
        ...and other stocks
      ],
      "futures":[
         {
            "stock":"YMW00:CBOT",
            "link":"https://www.google.com/finance/quote/YMW00:CBOT",
            "name":"Dow Futures",
            "price":"33766",
            "priceMovement":{
               "percentage":"0.5509068",
               "value":"185",
               "movement":"Up"
            }
         },
        ...and other stocks
      ]
   },
   "marketTrends":[
      {
         "title":"Americas",
         "link":"https://www.google.com/finance/markets/indexes/americas",
         "results":[
            {
               "stock":".INX:INDEXSP",
               "link":"https://www.google.com/finance/quote/.INX:INDEXSP",
               "name":"S&P 500",
               "price":"3,965.34",
               "priceMovement":{
                  "percentage":"0.48%",
                  "value":"+18.78",
                  "movement":"Up"
               }
            },
           ...and other stocks
         ]
      },
      ...and other regions
   ],
   "news":[
      {
         "source":"Investor's Business Daily",
         "link":"https://www.investors.com/market-trend/stock-market-today/dow-jones-futures-market-rally-faces-key-resistance-time-to-buy-apple-stock-or-short/",
         "date":"1 hour ago",
         "snippet":"Dow Jones Futures: Market Rally Faces Key Resistance; Time To Buy Apple \n""+""Stock — Or Short? | Investor's Business ...",
         "thumbnail":"https://encrypted-tbn2.gstatic.com/images?q=tbn:ANd9GcRVfTCLlCLoj0slVCJA8XImDiE6s4Tqf-nMDcrzDyvN6CePx9R0d0hDkE1gHNY",
         "stocks":[
            {
               "stock":".DJI:INDEXDJX",
               "link":"https://www.google.com/finance/quote/.DJI:INDEXDJX",
               "name":".DJI",
               "priceMovement":{
                  "percentage":"0.59%",
                  "movement":"Up"
               }
            },
            ...and other stocks
         ]
      },
    ...and other news
   ],
   "discoverMore":[
      {
         "stock":".INX:INDEXSP",
         "link":"https://www.google.com/finance/quote/.INX:INDEXSP",
         "name":"S&P 500",
         "price":"3,965.34",
         "priceMovement":{
            "percentage":"0.48%",
            "movement":"Up"
         }
      },
    ... and other stocks
   ]
}

```

## Links

- [Code in the online IDE](https://replit.com/@MikhailZub/Google-Finance-Main-Page-with-NodeJS-SerpApi#index.js)
- [Google Finance Markets API](https://serpapi.com/google-finance-markets)

If you want to see some projects made with SerpApi, [write me a message](mailto:miha01012019@gmail.com).

---

Join us on [Twitter](https://twitter.com/serp%5Fapi) | [YouTube](https://www.youtube.com/channel/UCUgIHlYBOD3yA3yDIRhg%5Fmg)

Add a [Feature Request](https://github.com/serpapi/public-roadmap/issues)💫 or a [Bug](https://github.com/serpapi/public-roadmap/issues)🐞