Web Scraping Google Finance Markets with Nodejs

What will be scraped

Using Google Finance Markets API 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:

npm i google-search-results-nodejs

Here's the full code example, if you don't need an explanation:

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 library and define new search instance with your API key from SerpApi:

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

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

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:

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:

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

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

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 method, which allows you to use an object with the necessary parameters to change default output options:

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

Output

{
   "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

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 packages cheerio to parse parts of the HTML markup, and axios to make a request to a website.

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

$ npm init -y

And then:

$ npm i cheerio axios

*If you don't have Node.js installed, you can download it from nodejs.org and follow the installation documentation.

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 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 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.

Code explanation

Declare constants from cheerio and axios libraries:

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

Next, we write the request options: HTTP headers with User-Agent which is used to act as a "real" user visit, and the necessary parameters for making a request:

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> so websites understand that it's a script that sends a request and might block it. Check what's your 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 request that has data key that we destructured and parse it with cheerio:

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() method) from all scripts tag from the page (with $() method) and find which of them contains "key: 'ds:6" string:

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() and indexOf() methods) and execute it (using 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):

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, then using spread syntax we make an array from an iterable iterator of matches, received from matchAll method.

Next, we take match results and make a new object with reduce method:

//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 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:

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:

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

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

//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:

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:

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:

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

Now we can launch our parser:

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

Output

{
   "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
   ]
}

If you want to see some projects made with SerpApi, write me a message.


Join us on Twitter | YouTube

Add a Feature RequestπŸ’« or a Bug🐞