All articles

Scraping Google Trends using Nodejs (Storing Data in CSV)

Published Date Feb 3, 2025
Read 9 min
Scraping Google Trends using Nodejs (Storing Data in CSV)

TL;DR

  • Node.js guide using Scrapingdog to pull Google Trends, then export CSV with fast-csv and plot a PNG chart via chartjs-node-canvas.

  • Example: “Air purifier” in India (2021–2026); code fetches time series and saves trends_chart.png.

  • Insight: interest rises in Sep and peaks around Nov; highest in Nov 2024.

  • Includes ready code and a 1,000-credit free trial to test.

The world is moving very fast and analyzing trends becomes very crucial. No matter what industry you work in, if you have real-time trends data it can give you a competitive advantage over others.

Google Trends provides in-depth data on any trend around the globe. It collects this data through Google Search Results. If you want to prepare a report on growing trends within multiple industries, scraping Google Trends would be quite efficient for building reports.

This article will scrape Google Trends data using Nodejs and Scrapingdog’s Google Trends API.

Setup & Installation

For extracting trends data we are going to use Nodejs. If it is not installed on your machine, you can download it here.

Then create a folder by any name you like.

1mkdir trends
2cd trends

Initialize the package.json file to establish a node project and create a js file. I am naming the file as trends.js.

1npm init

Now, we have to install four libraries that will be used in the course of this article.

1npm i axios fs chartjs-node-canvas fast-csv
  • axios is for making an HTTP connection with the API.

  • fs is for reading the JSON data received from the API.

  • chartjs-node-canvas generates the graph using Chart.js**.**

  • fast-csv saves the data to a CSV file.

The final step would be to sign up for the trial pack of Scrapingdog. The trial pack comes with 1000 free credits that can be used for testing any API from Scrapingdog.

Let’s say you work in a consumer electronic manufacturing sector and you want to analyze whether the usage of Air purifier will going to increase or not. To analyze consumer interests and demands we will scrape the trends data.

Here's a small video go through on how you can use Scrapigndog to scrape Google Trends.

Before we start coding, it would be great to read the documentation. This will help us understand the role of every parameter. We are going to analyze the trends of the keyword Air Purifier from 01 January 2021 to 01 January 2026 in India.

Let’s dive into our Scrapingdog’s dashboard and fill in the fields.

1 kT7yuvV9pCOTAcv5ybtsig

The best part is that after filling out the form you will get a ready-made code on the right.

1 pBqh8QZXM48t93StgfucNQ

Just copy this code and paste it into your working environment.

1//trends.js
2
3const axios = require('axios');
4
5const api_key = 'Your-API-Key';
6const url = 'https://api.scrapingdog.com/google_trends/';
7
8const params = {
9 api_key: api_key,
10 query: 'Air purifier',
11 language: 'en',
12 geo: 'IN',
13 region: '0',
14 data_type: 'TIMESERIES',
15 tz: '',
16 cat: '0',
17 gprop: '',
18 date: '2021-01-01 2025-01-01'
19};
20
21axios
22 .get(url, { params: params })
23 .then(function (response) {
24 if (response.status === 200) {
25 const data = response.data;
26 console.log(data);
27 } else {
28 console.log('Request failed with status code: ' + response.status);
29 }
30 })
31 .catch(function (error) {
32 console.error('Error making the request: ' + error.message);
33 });

The code is very simple but let me explain you step by step.

If you see the params object you will find that we have almost passed 10 parameters. Let me explain to you the meaning of each parameter.

  • api_key is the API key for your Scrapingdog account.

  • query is the term you want to search for.

  • language is the language of the result.

  • geo is the country you are targeting.

  • region is the place you are targeting using the geo parameter.

  • data_type defines the type of search you want to do.

  • tz is the time zone.

  • cat is used for defining the search category.

  • gprop is used to sort results by property.

  • date is the date range.

If you run this code you will get this data.

1 1LgvFYZzLycsWYVqcrGREQ

According to Google Trends, value means this…

1 n tomMEyaOnOjm0rPEGARA

That means higher the value of value higher the demand.

Let’s plot a graph using chartjs-node-canvas. This will help us visualize the demand. We have to modify the code a little to make it the code look more readable.

1const axios = require('axios');
2const fs = require("fs");
3const { ChartJSNodeCanvas } = require("chartjs-node-canvas");
4const fastCsv = require("fast-csv");
5const path = require("path");
6
7let data;
8const api_key = 'your-api-key';
9const url = 'https://api.scrapingdog.com/google_trends/';
10
11const params = {
12 api_key: api_key,
13 query: 'Air purifier',
14 language: 'en',
15 geo: 'IN',
16 data_type: 'TIMESERIES',
17 tz: '',
18 category: '0',
19 gprop: '',
20 date: '2021-01-01 2025-01-01'
21};
22let TrendsData
23
24async function fetchData() {
25 try{
26 TrendsData = await axios.get(url, { params: params })
27 if (TrendsData.status === 200) {
28 data = TrendsData.data["interest_over_time"]["timeline_data"];
29 let dates = data.map(entry => entry["date"]);
30 let values = data.map(entry => parseInt(entry["values"][0]["value"]));
31 console.log("Data is Extracted, now ploting the graph");
32
33 let graphStatus = await generateChart(dates,values)
34 if(graphStatus){
35 console.log('graph plotting is complete')
36 }
37
38
39 } else {
40 console.log('Request failed with status code: ' + TrendsData.status);
41 }
42 }catch(err){
43 console.error('Error making the request: ' + err.message);
44 }
45}
46
47
48
49async function generateChart(dates,values) {
50 const width = 800;
51 const height = 400;
52
53 const chartCanvas = new ChartJSNodeCanvas({ width, height });
54
55 const configuration = {
56 type: "line",
57 data: {
58 labels: dates,
59 datasets: [
60 {
61 label: "Search Interest in 'Air Purifier'",
62 data: values,
63 borderColor: "blue",
64 fill: false,
65 tension: 0.3,
66 },
67 ],
68 },
69 options: {
70 responsive: false,
71 plugins: {
72 title: {
73 display: true,
74 text: "Google Trends: Air Purifier Search Interest Over Time",
75 font: { size: 16 },
76 },
77 },
78 scales: {
79 x: { title: { display: true, text: "Date" } },
80 y: { title: { display: true, text: "Search Interest" } },
81 },
82 },
83 };
84
85 // Generate and save chart as an image
86 const imagePath = path.join(__dirname, "trends_chart.png");
87 const imageBuffer = await chartCanvas.renderToBuffer(configuration);
88 fs.writeFileSync(imagePath, imageBuffer);
89
90 console.log(`Chart saved as ${imagePath}`);
91 return true
92 }
93
94fetchData()

After data extraction is over we call the generateChart function. After setting the height and width of the graph we are creating an object that will design the graph. Once the plotting is done we save the graph as a PNG file by the name trends_chart.png.

Let’s run the code and see what it looks like.

1 cXoTpLMR17A80MetwA839Q

It clearly shows that trends started picking up after September 2024 and peaked around November 2024. If you notice the entire graph you will notice that the graph peaks around the same time interval. It starts growing by September and peaks in the month of November.

Key Findings:

  • Highest Search Interest100 (Peak in November 2024)

  • Lowest Search Interest5 (Observed in September 2023)

  • Average Search Interest10.98 across all data points

Storing the data into a CSV file

Here we will use fast-csv library to simply store the data into a CSV file.

1const axios = require('axios');
2const fs = require("fs");
3const { ChartJSNodeCanvas } = require("chartjs-node-canvas");
4const fastCsv = require("fast-csv");
5const path = require("path");
6
7let data;
8const api_key = 'your-api-key';
9const url = 'https://api.scrapingdog.com/google_trends/';
10
11const params = {
12 api_key: api_key,
13 query: 'Air purifier',
14 language: 'en',
15 geo: 'IN',
16 data_type: 'TIMESERIES',
17 tz: '',
18 category: '0',
19 gprop: '',
20 date: '2021-01-01 2025-01-01'
21};
22let TrendsData
23
24async function fetchData() {
25 try{
26 TrendsData = await axios.get(url, { params: params })
27 if (TrendsData.status === 200) {
28 data = TrendsData.data["interest_over_time"]["timeline_data"];
29 let dates = data.map(entry => entry["date"]);
30 let values = data.map(entry => parseInt(entry["values"][0]["value"]));
31 console.log("Data is Extracted, now ploting the graph");
32
33 let graphStatus = await generateChart(dates,values)
34 if(graphStatus){
35 console.log('graph plotting is complete')
36 }
37
38 let csvStatus = await saveCSV(dates,values)
39 if(csvStatus){
40 console.log('CSV file is created')
41 }
42 } else {
43 console.log('Request failed with status code: ' + TrendsData.status);
44 }
45 }catch(err){
46 console.error('Error making the request: ' + err.message);
47 }
48}
49
50
51
52async function generateChart(dates,values) {
53 const width = 800;
54 const height = 400;
55
56 const chartCanvas = new ChartJSNodeCanvas({ width, height });
57
58 const configuration = {
59 type: "line",
60 data: {
61 labels: dates,
62 datasets: [
63 {
64 label: "Search Interest in 'Air Purifier'",
65 data: values,
66 borderColor: "blue",
67 fill: false,
68 tension: 0.3,
69 },
70 ],
71 },
72 options: {
73 responsive: false,
74 plugins: {
75 title: {
76 display: true,
77 text: "Google Trends: Air Purifier Search Interest Over Time",
78 font: { size: 16 },
79 },
80 },
81 scales: {
82 x: { title: { display: true, text: "Date" } },
83 y: { title: { display: true, text: "Search Interest" } },
84 },
85 },
86 };
87
88 // Generate and save chart as an image
89 const imagePath = path.join(__dirname, "trends_chart.png");
90 const imageBuffer = await chartCanvas.renderToBuffer(configuration);
91 fs.writeFileSync(imagePath, imageBuffer);
92
93 console.log(`Chart saved as ${imagePath}`);
94 return true
95 }
96
97async function saveCSV(dates,values) {
98 const csvPath = path.join(__dirname, "air_purifier_trends.csv");
99 const writeStream = fs.createWriteStream(csvPath);
100 const csvStream = fastCsv.format({ headers: true });
101
102 csvStream.pipe(writeStream);
103 dates.forEach((date, index) => {
104 csvStream.write({ Date: date, Interest: values[index] });
105 });
106
107 csvStream.end();
108
109 console.log(`CSV saved at ${csvPath}`);
110
111 return true;
112}
113
114
115fetchData()

Here we will use fast-csv library to simply store the data into a CSV file.

fs.createWriteStream(csvPath) creates a writable stream to write data to the CSV file. Pipes (.pipe()) the formatted CSV data into the writable file stream (writeStream), allowing for efficient data writing.

Once you run the code you will see a CSV file inside your folder.

Observations

🔹Marketing & Sales Timing:

  • The best time to promote air purifiers is October–December when search interest is at its highest.

  • Advertising campaigns should be intensified in September to capture early buyers before peak demand.

🔹 Content Strategy for SEO:

  • Publish seasonal blog posts about air quality concerns and solutions before the peak season (August–September).

  • Focus on health benefits, pollution reports, and expert recommendations in October–November.

🔹 Product Launches & Discounts:

  • Introduce limited-time promotions in October-November to capitalize on peak interest.

  • Offer special bundles or discounts around Black Friday and Cyber Monday.

Here are Some Key Takeaways:

  • You can automate Google Trends data collection using Node.js instead of manually checking trends in the browser.

  • The guide provides a working Node.js script to fetch trend data and export it into a CSV file for analysis.

  • It demonstrates how to extract different types of trend insights, such as interest over time and regional interest.

  • Automating Google Trends scraping helps in building keyword research reports and spotting rising trends faster.

  • The tutorial is designed to help developers integrate trend data directly into their own tools and workflows.

Conclusion

Tracking Google Trends data for ‘Air Purifier’ searches provides valuable insights into consumer behavior, seasonal demand, and market opportunities. By leveraging Scrapingdog’s Google Trends API and automating data extraction with Node.js, we successfully visualized the search interest over time.

By storing and analyzing Google Trends data, businesses can predict consumer demand, refine their marketing efforts, and stay ahead of competitors. Future improvements could include correlating this data with pollution levels, e-commerce sales, or weather patterns to gain deeper insights.

Frequently Asked Questions (FAQs)

You can scrape Google Trends using Node.js by integrating the Scrapingdog API. Fetch trends data for any keyword, export it to a CSV file, and visualize it using libraries like Chart.js or chartjs-node-canvas.

Yes, Scrapingdog requires an API key. Sign up for a free trial to get 1000 credits, which allows you to test scraping Google Trends and integrate it with your Node.js projects.

Scraping Google Trends helps businesses identify seasonal demand, track consumer interests, optimize marketing campaigns, and make data-driven decisions to stay ahead of competitors.

Additional Resources

Try Scrapingdog for Free!

Get 200 free credits to spin the API. No credit card required!