I have a project, which one of the part is automate the process of taking the Interest Over Time chart data from Google Trends and put it on Google Sheet
I need the search trends from 1 year ago - present
Interest Over Time Chart - Google Trends
I already tried Pytrends, but not accurate compared to the G-Trends itself. I also tried using other scripts, but turned out Error 400 (Bad Request)
I just want to automatically get the CSV file and paste the data into the Sheet every time I change the keyword on the dashboard and trigger the button
Hope you guys can help me, cause this project is very important for me and my team. Thank you so much!
- Pytrends, but the result is not accurate compared to Google Trends itself
- Using Google Apps Script to get data from https://trends.google.com/trends/api/widgetdata/multiline/csv. But turned out Error 400 (Bad Request)
Script Used :
function updateResults() {
// Get the criteria from the Criteria sheet
var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Criteria");
var keywords = sheet.getRange("E1:E5").getValues();
var country = sheet.getRange("G1").getValue();
var startDate = sheet.getRange("B7").getValue();
var endDate = sheet.getRange("B8").getValue();
// Format the start and end dates
var formattedStartDate = Utilities.formatDate(new Date(startDate), Session.getScriptTimeZone(), "yyyy-MM-dd");
var formattedEndDate = Utilities.formatDate(new Date(endDate), Session.getScriptTimeZone(), "yyyy-MM-dd");
// Fetch the data from Google Trends
var trendsData = UrlFetchApp.fetch("https://trends.google.com/trends/api/widgetdata/multiline/csv?hl=en-US&tz=-480&req=%7B%22time%22%3A%22" + formattedStartDate + "%20" + formattedEndDate + "%22%2C%22resolution%22%3A%22WEEK%22%2C%22locale%22%3A%22en-US%22%2C%22comparisonItem%22%3A%5B%7B%22geo%22%3A%7B%22country%22%3A%22" + country + "%22%7D%2C%22complexKeywordsRestriction%22%3A%7B%22keyword%22%3A%5B" + encodeURIComponent(keywords.join(",")) + "%5D%7D%7D%5D%2C%22requestOptions%22%3A%7B%22property%22%3A%22%22%2C%22backend%22%3A%22IZG%22%2C%22category%22%3A0%7D%7D&token=APP6_UEAAAAAXuzScgW_HxJprzdTK51Hw2k0LgMXWjJv");
// Parse the data and update the Results sheet
var data = Utilities.parseCsv(trendsData.getContentText());
var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Results");
for (var i = 1; i < data.length; i++) {
sheet.getRange(i, 1).setValue(parseDate(data[i][0]));
for (var j = 1; j < data[i].length; j++) {
sheet.getRange(i, j + 1).setValue(data[i][j]);
}
}
}
// Parses a date in the format "YYYY-MM-DD" and returns a Date object
function parseDate(dateString) {
var parts = dateString.split("-");
return new Date(parts[0], parts[1] - 1, parts[2]);}