GithubHelp home page GithubHelp logo

pat310 / google-trends-api Goto Github PK

View Code? Open in Web Editor NEW
873.0 40.0 174.0 2.23 MB

An API layer on top of google trends

Home Page: https://www.npmjs.com/package/google-trends-api

License: MIT License

JavaScript 100.00%
google-trends

google-trends-api's Introduction

google-trends-api

NPM

npm version Build status Coverage Status Code Climate Dependency Status Known Vulnerabilities

v3 to v4

Big changes! The old google-trends endpoints are deprecated and are heavily throttled so this library has changed significantly. You can choose to download the old version via npm install [email protected] but it is discouraged.

Introduction

This library provides an API layer to google trends data. Due to CORS restrictions, this library is intended to be used in node. It is constantly being expanded and improved so please check back frequently. Also, please feel free to contribute to make the library even better! ๐Ÿถ

Syntax

const googleTrends = require('google-trends-api');

googleTrends.apiMethod(optionsObject, [callback])

Parameters

optionsObject An object with the following options keys:

  • keyword Target search term(s) string or array if you wish to compare search terms required
  • startTime Start of time period of interest (new Date() object). If startTime is not provided, a date of January 1, 2004 is assumed (this is the oldest available google trends data)
  • endTime End of time period of interest (new Date() object). If endTime is not provided, the current date is selected.
  • geo Location of interest (string or array if you wish to provide separate locations for each keyword).
  • hl Preferred language (string defaults to english)
  • timezone Timezone (number defaults to the time zone difference, in minutes, from UTC to current locale (host system settings))
  • category Category to search within (number defaults to all categories)
  • property Google property to filter on. Defaults to web search. (enumerated string ['images', 'news', 'youtube' or 'froogle'] where froogle is Google Shopping results)
  • resolution Granularity of the geo search (enumerated string ['COUNTRY', 'REGION', 'CITY', 'DMA']). resolution is specific to the interestByRegion method.
  • granularTimeResolution Boolean that dictates if the results should be given in a finer time resolution (if startTime and endTime is less than one day, this should be set to true)

callback Optional callback function where the first parameter is an error and the second parameter is the result. If no callback is provided, then a promise is returned.

Table of contents


Installation

To install this package, clone this git repository and include it in your project's node_modules or simply:

npm install google-trends-api

Require google-trends-api in your script and give it a variable name:

const googleTrends = require('google-trends-api');

You will now be able to access methods on googleTrends. See the API Methods section below to see the methods available and their syntax.

back to top


API

Promises

By default, all the API's return a promise for the results. Example:

googleTrends.interestOverTime({keyword: 'Women\'s march'})
.then(function(results){
  console.log('These results are awesome', results);
})
.catch(function(err){
  console.error('Oh no there was an error', err);
});

Callbacks

All API methods can alternatively take a callback function as the second parameter. For example:

googleTrends.interestOverTime({keyword: 'Women\'s march'}, function(err, results){
  if(err) console.error('there was an error!', err);
  else console.log('my sweet sweet results', results);
})

Proxy Server

A proxy server can be used by specifying an http agent as part of the query. This example uses https-proxy-agent

const HttpsProxyAgent = require('https-proxy-agent');

let proxyAgent =  new HttpsProxyAgent('http://proxy-host:8888/');

let query = {
    keyword: 'Women\'s march',
    agent: proxyAgent
};

googleTrends.interestOverTime(query)
.then(function(results){
  console.log('These proxied results are incredible', results);
})
.catch(function(err){
  console.error('Oh no there was an error, double check your proxy settings', err);
});

Multiple Keywords

Compare multiple keywords with any of the api methods by supplying an array instead of a single string

googleTrends.interestOverTime({keyword: ['Women\'s march', 'Trump Inauguration']})
.then(function(results){
  console.log('These results are awesome', results);
})
.catch(function(err){
  console.error('Oh no there was an error', err);
});

Examples

There are examples available for each API method in the root directory of the module. Note: Each example in examples.js needs to be uncommented.

API Methods

The following API methods are available:

  • autoComplete: Returns the results from the "Add a search term" input box in the google trends UI. These results (Topics) can then be used in the other API methods. Note: Search terms and Topics are measured differently, so relatedTopics will not work with comparisons that contain both Search terms and Topics.

  • dailyTrends: Daily Search Trends highlights searches that jumped significantly in traffic among all searches over the past 24 hours and updates hourly. These search trends show the specific queries that were searched, and the absolute number of searches made. 20 daily trending search results are returned.You can search retroactively for up to 15 days in the past.

  • interestOverTime: Numbers represent search interest relative to the highest point on the chart for the given region and time. A value of 100 is the peak popularity for the term. A value of 50 means that the term is half as popular. Likewise a score of 0 means the term was less than 1% as popular as the peak. If you use multiple keywords for a comparison, the return data will also contain an average result for each keyword.

  • interestByRegion: See in which location your term was most popular during the specified time frame. Values are calculated on a scale from 0 to 100, where 100 is the location with the most popularity as a fraction of total searches in that location, a value of 50 indicates a location which is half as popular, and a value of 0 indicates a location where the term was less than 1% as popular as the peak.

    Note: A higher value means a higher proportion of all queries, not a higher absolute query count. So a tiny country where 80% of the queries are for "bananas" will get twice the score of a giant country where only 40% of the queries are for "bananas".

  • realTimeTrends: Realtime Search Trends highlight stories that are trending across Google surfaces within the last 24 hours, and are updated in realtime. These stories are a collection of Knowledge Graph topics, Search interest, trending YouTube videos, and/or Google News articles detected by Google's algorithms. 13 real time trending stories are returned.

  • relatedQueries: Users searching for your term also searched for these queries. The following metrics are returned:

    • Top - The most popular search queries. Scoring is on a relative scale where a value of 100 is the most commonly searched query, 50 is a query searched half as often, and a value of 0 is a query searched for less than 1% as often as the most popular query.
    • Rising - Queries with the biggest increase in search frequency since the last time period. Results marked "Breakout" had a tremendous increase, probably because these queries are new and had few (if any) prior searches.
  • relatedTopics: Users searching for your term also searched for these topics. The following metrics are returned:

    • Top - The most popular topics. Scoring is on a relative scale where a value of 100 is the most commonly searched topic, a value of 50 is a topic searched half as often, and a value of 0 is a topic searched for less than 1% as often as the most popular topic.
    • Rising - Related topics with the biggest increase in search frequency since the last time period. Results marked "Breakout" had a tremendous increase, probably because these topics are new and had few (if any) prior searches.

back to top


autoComplete

  • Results from the "add a search term" input box in the google trends UI*

Syntax

googleTrends.autoComplete({keyword: string}, cbFunc)

Requires an object as the first parameter with the following keys:

  • keyword - required - type string - the search term of interest
  • hl - optional - type string - preferred language code for results (defaults to english)

Optional callback function as the second parameter (otherwise returns a promise)

Example

Returning the auto-complete results for 'Back to School'

Input
googleTrends.autoComplete({keyword: 'Back to School'})
.then(function(results) {
  console.log(results);
})
.catch(function(err) {
  console.error(err);
})
Output
{"default":{"topics":[{"mid":"/m/0414j6","title":"Back to School","type":"1986 film"},{"mid":"/m/068pw8","title":"Back to school","type":"Topic"},{"mid":"/m/04vwgn","title":"Fight Back to School","type":"1991 film"},{"mid":"/m/05357_","title":"Tax holiday","type":"Holiday"},{"mid":"/m/02pb6kt","title":"Fight Back to School II","type":"1992 film"}]}}

Note: You can then use these results in the other API methods. For example, if you wanted interestOverTime for 'Back to School' where the type is 'Topic', you would then use: googleTrends.interestOverTime({keyword: '/m/068pw8'})

back to top


dailyTrends

Daily Search Trends highlights searches that jumped significantly in traffic among all searches over the past 24 hours and updates hourly. These search trends show the specific queries that were searched, and the absolute number of searches made. 20 daily trending search results are returned

Syntax

googleTrends.dailyTrends({ geo: string }, cbFunc)

Requires an object as the first parameter with the following keys:

  • geo - required - type string - geocode for a country. For example, geo: 'US' will target United States or geo: 'FR' will target France.
  • hl - optional - type string - preferred language code for results (defaults to english).
  • timezone - optional - type number - preferred timezone (defaults to the time zone difference, in minutes, from UTC to current locale (host system settings))
  • trendDate - optional - type Date object - the date you are interesting in retrieving trends information for (defaults to the current date). Note that querying for a date more than 15 days in the past will result in an error.

Optional callback function as the second parameter (otherwise returns a promise)

Example

Returning real time trending stories for the United States region.

Input
googleTrends.dailyTrends({
  trendDate: new Date('2019-01-10'),
  geo: 'US',
}, function(err, results) {
  if (err) {
    console.log(err);
  }else{
    console.log(results);
  }
});
Output
{
  default : [Object]{
    trendingSearchesDays : [Array]
      [0] : [Object]{
        date : String
        formattedDate: String
        trendingSearches : [Array]{
          [0] : [Object] //First trending result
        }
      [1] : [Object]{
        date : String
        formattedDate: String
        trendingSearches : [Array]{
          [0] : [Object] //first trending result
          ...
          [19] : [Object] //20th trending result
        }
      }
    }
    endDateForNextRequest : String,
    rssFeedPageUrl : String,
  }
}

back to top


interestOverTime

Search interest relative to the highest point on the chart for the given region and time (100 is the peak popularity for the term)

Syntax

googleTrends.interestOverTime({keyword: string, startTime: Date, endTime: Date, geo: string}, cbFunc)

Requires an object as the first parameter with the following keys:

  • keyword - required - type string or array - the search term(s) of interest
  • startTime - optional - type Date object - the start of the time range of interest (defaults to new Date('2004-01-01') if not supplied)
  • endTime - optional - type Date object - the end of the time range of interest (defaults to new Date(Date.now()) if not supplied)
  • geo - optional - type string or array - geocode(s) for a country, region, or DMA depending on the granularity required (defaults to worldwide). For example, geo: 'US-CA-800' will target the Bakersfield, California, United States or geo: 'US' will just target the US. Passing geo: ['US-CA, US-VA'], keyword: ['wine', 'peanuts'] will search for wine in California and peanuts in Virginia.
  • hl - optional - type string - preferred language code for results (defaults to english)
  • timezone - optional - type number - preferred timezone (defaults to the time zone difference, in minutes, from UTC to current locale (host system settings))
  • category - optional - type number - a number corresponding to a particular category to query within (defaults to all categories), see the category wiki for a complete list
  • granularTimeResolution - optional - type boolean - if true, will try to return results to a finer time resolution (only relevant for startTime and endTime less than one week)

Optional callback function as the second parameter (otherwise returns a promise)

The resolution of the search changes automatically depending on the search duration. The wider the duration window, the worse the resolution (for example, a search duration with a startTime and endTime that ends years apart will return a resolution in months, while a search duration with a startTime and endTime a few hours apart will return a resolution in minutes).

Example 1

Returning the search interest over time for 'Valentines Day' (by default from 2004-01-01 to today)

Input
googleTrends.interestOverTime({keyword: 'Valentines Day'})
.then(function(results){
  console.log(results);
})
.catch(function(err){
  console.error(err);
});
Output
{"default":{"timelineData":[{"time":"1072915200","formattedTime":"Jan 2004","formattedAxisTime":"Jan 1, 2004","value":[26],"formattedValue":["26"]},{"time":"1075593600","formattedTime":"Feb 2004","formattedAxisTime":"Feb 1, 2004","value":[74],"formattedValue":["74"]},
...
{"time":"1483228800","formattedTime":"Jan 2017","formattedAxisTime":"Jan 1, 2017","value":[18],"formattedValue":["18"]},{"time":"1485907200","formattedTime":"Feb 2017","formattedAxisTime":"Feb 1, 2017","value":[72],"formattedValue":["72"]}],"averages":[]}}
Example 2

Returning the search interest over time for 'Valentines Day' from the past four hours. Note that the resolution is by minute since our query duration is shorter.

Input
googleTrends.interestOverTime({keyword: 'Valentines Day', startTime: new Date(Date.now() - (4 * 60 * 60 * 1000))}, function(err, results) {
  if (err) console.log('oh no error!', err);
  else console.log(results);
});
Output
{"default":{"timelineData":[{"time":"1487026800","formattedTime":"Feb 13, 2017 at 6:00 PM","formattedAxisTime":"6:00 PM","value":[49],"formattedValue":["49"]},{"time":"1487026860","formattedTime":"Feb 13, 2017 at 6:01 PM","formattedAxisTime":"6:01 PM","value":[50],"formattedValue":["50"]},
...
{"time":"1487040180","formattedTime":"Feb 13, 2017 at 9:43 PM","formattedAxisTime":"9:43 PM","value":[88],"formattedValue":["88"]},{"time":"1487040240","formattedTime":"Feb 13, 2017 at 9:44 PM","formattedAxisTime":"9:44 PM","value":[81],"formattedValue":["81"]}],"averages":[]}}

back to top


interestByRegion

See in which location your term was most popular during the specified time frame. Values are calculated on a scale from 0 to 100, where 100 is the location with the most popularity as a fraction of total searches in that location.

Syntax

googleTrends.interestByRegion({keyword: string, startTime: Date, endTime: Date, geo: string, resolution: string}, cbFunc)

Requires an object as the first parameter with the following keys:

  • keyword - required - type string or array - the search term(s) of interest
  • startTime - optional - type Date object - the start of the time range of interest (defaults to new Date('2004-01-01') if not supplied)
  • endTime - optional - type Date object - the end of the time range of interest (defaults to new Date(Date.now()) if not supplied)
  • geo - optional - type string or array - geocode(s) for a country, region, or DMA depending on the granularity required (defaults to worldwide). For example, geo: 'US-CA-800' will target the Bakersfield, California, United States or geo: 'US' will just target the US. Passing geo: ['US-CA, US-VA'], keyword: ['wine', 'peanuts'] will search for wine in California and peanuts in Virginia.
  • resolution - optional - type enumerated string either COUNTRY, REGION, CITY or DMA. Resolution is selected by default otherwise. Trying to select a resolution larger than a specified geo will return an error.
  • hl - optional - type string - preferred language code for results (defaults to english) for results (defaults to english)
  • timezone - optional - type number - preferred timezone (defaults to the time zone difference, in minutes, from UTC to current locale (host system settings))
  • category - optional - type number - a number corresponding to a particular category to query within (defaults to all categories), see the category wiki for a complete list

Optional callback function as the second parameter (otherwise returns a promise)

Example 1

Returning the search interest by cities around the world for 'Donald Trump' from February 01, 2017 to February 06, 2017.

Input
googleTrends.interestByRegion({keyword: 'Donald Trump', startTime: new Date('2017-02-01'), endTime: new Date('2017-02-06'), resolution: 'CITY'})
.then((res) => {
  console.log(res);
})
.catch((err) => {
  console.log(err);
})
Output
{"default":{"geoMapData":[{"coordinates":{"lat":18.594395,"lng":-72.3074326},"geoName":"Port-au-Prince","value":[100],"formattedValue":["100"],"maxValueIndex":0},{"coordinates":{"lat":43.467517,"lng":-79.6876659},"geoName":"Oakville","value":[90],"formattedValue":["90"],"maxValueIndex":0},
...
{"coordinates":{"lat":40.9312099,"lng":-73.8987469},"geoName":"Yonkers","value":[69],"formattedValue":["69"],"maxValueIndex":0}]}}
Example 2

Returning the search interest by cities in California for 'Donald Trump' from February 01, 2017 to February 06, 2017.

Input
googleTrends.interestByRegion({keyword: 'Donald Trump', startTime: new Date('2017-02-01'), endTime: new Date('2017-02-06'), geo: 'US-CA'})
.then((res) => {
  console.log(res);
})
.catch((err) => {
  console.log(err);
})
Output
{"default":{"geoMapData":[{"geoCode":"807","geoName":"San Francisco-Oakland-San Jose CA","value":[100],"formattedValue":["100"],"maxValueIndex":0},{"geoCode":"828","geoName":"Monterey-Salinas CA","value":[100],"formattedValue":["100"],"maxValueIndex":0},
...
{"geoCode":"811","geoName":"Reno NV","value":[12],"formattedValue":["12"],"maxValueIndex":0},{"geoCode":"813","geoName":"Medford-Klamath Falls OR","value":[4],"formattedValue":["4"],"maxValueIndex":0}]}}

back to top


realtimeTrends

Realtime Search Trends highlight stories that are trending across Google surfaces within the last 24 hours, and are updated in realtime. 13 real time trending stories are returned

Syntax

googleTrends.realTimeTrends({ geo: string }, cbFunc)

Requires an object as the first parameter with the following keys:

  • geo - required - type string - geocode for a country. For example, geo: 'US' will target United States or geo: 'FR' will target France.
  • hl - optional - type string - preferred language code for results (defaults to english) for results (defaults to english)
  • timezone - optional - type number - preferred timezone (defaults to the time zone difference, in minutes, from UTC to current locale (host system settings))
  • category - optional - type string - a string corresponding to a particular category to query within (defaults to all categories): All : 'all' Entertainment: 'e' Business : 'b' Science/Tech : 't' Health : 'm' Sports : 's' Top Stories : 'h'

Optional callback function as the second parameter (otherwise returns a promise)

Example

Returning real time trending stories for the United States region.

Input
googleTrends.realTimeTrends({
    geo: 'US',
    category: 'all',
}, function(err, results) {
    if (err) {
       console.log(err);
    } else {
      console.log(results);
    } 
});
Output
{
	featuredStoryIds : [Array], // Empty
	trendingStoryIds : [Array], // 300 trending story IDs
  storySummaries : [Object]
    {
	  featuredStories : [Array], // Empty
    trendingStories : [Array], // 13 top trending stories
    },
	date : "Date-String",
  hideAllImages : Boolean,
}

back to top


relatedQueries

Users searching for your term also searched for these queries.

Syntax

googleTrends.relatedQueries({keyword: string, startTime: Date, endTime: Date, geo: string}, cbFunc)

Requires an object as the first parameter with the following keys:

  • keyword - required - type string or array - the search term(s) of interest
  • startTime - optional - type Date object - the start of the time range of interest (defaults to new Date('2004-01-01') if not supplied)
  • endTime - optional - type Date object - the end of the time range of interest (defaults to new Date(Date.now()) if not supplied)
  • geo - optional - type string or array - geocode(s) for a country, region, or DMA depending on the granularity required (defaults to worldwide). For example, geo: 'US-CA-800' will target the Bakersfield, California, United States or geo: 'US' will just target the US. Passing geo: ['US-CA, US-VA'], keyword: ['wine', 'peanuts'] will search for wine in California and peanuts in Virginia.
  • hl - optional - type string - preferred language code for results (defaults to english) for results (defaults to english)
  • timezone - optional - type number - preferred timezone (defaults to the time zone difference, in minutes, from UTC to current locale (host system settings))
  • category - optional - type number - a number corresponding to a particular category to query within (defaults to all categories), see the category wiki for a complete list

Optional callback function as the second parameter (otherwise returns a promise)

Example

Returning top related queries for 'Westminster Dog show' with default startTime, endTime, and geo categories

Input
googleTrends.relatedQueries({keyword: 'Westminster Dog Show'})
.then((res) => {
  console.log(res);
})
.catch((err) => {
  console.log(err);
})
Output
{"default":{"rankedList":[{"rankedKeyword":[{"query":"dog show 2016","value":100,"formattedValue":"100","link":"/"},{"query":"2016 westminster dog show","value":95,"formattedValue":"95","link":"/"},
...
{"query":"dogs","value":20,"formattedValue":"20","link":"/"}]},{"rankedKeyword":[{"query":"dog show 2016","value":836500,"formattedValue":"Breakout","link":"/"},{"query":"2016 westminster dog show","value":811550,"formattedValue":"Breakout","link":"/"},
...
{"query":"who won the westminster dog show","value":59000,"formattedValue":"Breakout","link":"/"}]}]}}

back to top


relatedTopics

Users searching for your term also searched for these topics

Syntax

googleTrends.relatedTopics({keyword: string, startTime: Date, endTime: Date, geo: string}, cbFunc)

Requires an object as the first parameter with the following keys:

  • keyword - required - type string or array - the search term(s) of interest
  • startTime - optional - type Date object - the start of the time range of interest (defaults to new Date('2004-01-01') if not supplied)
  • endTime - optional - type Date object - the end of the time range of interest (defaults to new Date(Date.now()) if not supplied)
  • geo - optional - type string or array - geocode(s) for a country, region, or DMA depending on the granularity required (defaults to worldwide). For example, geo: 'US-CA-800' will target the Bakersfield, California, United States or geo: 'US' will just target the US. Passing geo: ['US-CA, US-VA'], keyword: ['wine', 'peanuts'] will search for wine in California and peanuts in Virginia.
  • hl - optional - type string - preferred language code for results (defaults to english) for results (defaults to english)
  • timezone - optional - type number - preferred timezone (defaults to the time zone difference, in minutes, from UTC to current locale (host system settings))
  • category - optional - type number - a number corresponding to a particular category to query within (defaults to all categories), see the category wiki for a complete list

Optional callback function as the second parameter (otherwise returns a promise)

Example

Returning top related topics for 'Chipotle' from January 1st, 2015 to February 10th, 2017.

Input
googleTrends.relatedTopics({keyword: 'Chipotle', startTime: new Date('2015-01-01'), endTime: new Date('2017-02-10')})
.then((res) => {
  console.log(res);
})
.catch((err) => {
  console.log(err);
})
Output
{"default":{"rankedList":[{"rankedKeyword":[{"topic":{"mid":"/m/01b566","title":"Chipotle Mexican Grill","type":"Restaurant company"},"value":100,"formattedValue":"100","link":"/"},{"topic":{"mid":"/m/02f217","title":"Chipotle","type":"Jalape\u00f1o"},"value":5,"formattedValue":"5","link":"/"},
...
{"topic":{"mid":"/m/01xg7s","title":"Chorizo","type":"Topic"},"value":0,"formattedValue":"0","link":"/"}]},{"rankedKeyword":[{"topic":{"mid":"/m/09_yl","title":"E. coli","type":"Bacteria"},"value":40700,"formattedValue":"Breakout","link":"/"},
...
{"topic":{"mid":"/m/0dqc4","title":"Caridea","type":"Animal"},"value":40,"formattedValue":"+40%","link":"/"}]}]}}

back to top



Geo help

Unfortunately support is not offered for zip codes at this time. The user must enter a country code, region (or state) code, and/or DMA (Designated Market Area) code.


Big Thanks

back to top

google-trends-api's People

Contributors

colibry-source avatar fohlen avatar ishtartec avatar jermenkoo avatar jtalen avatar pat310 avatar splatcollision avatar stephenmathieson avatar stonecypher avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

google-trends-api's Issues

No 'Access-Control-Allow-Origin' header is present on the requested resource.

Hi.

I am following the instructions in the readme file. but the examples are not working.
For instance,

googleTrends.autoComplete({keyword: 'Back to School'}) .then(function(results) { console.log(results); }) .catch(function(err) { console.error(err); })

Give the following error on console page.

capture

Can anyone say what's wrong?

Thank's :)

Knowledge Sharing between packages

Hey @pat310 I maintain the following Python implementation of Google Trends API.

https://github.com/GeneralMills/pytrends

I really like what you've done with your JavaScript version. I just wanted to say that I will be keeping an eye on yours for new features to add to mine and that you should do the same!

In particular I've added suggestions() method that helps users refine their keyword searches by providing more detailed terms to use.

Support for keyword comparison: averages?

Just a quick question. Does this api allow me to get the average values for the comparison of two keywords for a given time period? I couldn't find it in the readme. Thanks!

topRelated calls exceeded the Quota

How it have a Quota if i don't enter an api key?

[ Error: Quota limit exceeded, try again later
at parseHtml (/Users/name/Desktop/apiproject/node_modules/google-trends-api/lib/resources/htmlParser.js:5:46)
at /Users/name/Desktop/apiproject/node_modules/google-trends-api/lib/utils/topRelated.js:25:11
at tryCatcher (/Users/name/Desktop/apiproject/node_modules/bluebird/js/release/util.js:16:23)
at Promise._settlePromiseFromHandler (/Users/name/Desktop/apiproject/node_modules/bluebird/js/release/promise.js:510:31)
at Promise._settlePromise (/Users/name/Desktop/apiproject/node_modules/bluebird/js/release/promise.js:567:18)
at Promise._settlePromise0 (/Users/name/Desktop/apiproject/node_modules/bluebird/js/release/promise.js:612:10)
at Promise._settlePromises (/Users/name/Desktop/apiproject/node_modules/bluebird/js/release/promise.js:691:18)
at Async._drainQueue (/Users/name/Desktop/apiproject/node_modules/bluebird/js/release/async.js:138:16)
at Async._drainQueues (/Users/name/Desktop/apiproject/node_modules/bluebird/js/release/async.js:148:10)
at Immediate.Async.drainQueues (/Users/name/Desktop/apiproject/node_modules/bluebird/js/release/async.js:17:14)
at runCallback (timers.js:574:20)
at tryOnImmediate (timers.js:554:5)
at processImmediate [as _immediateCallback] (timers.js:533:5),
Error: Quota limit exceeded, try again later
at parseHtml (/Users/name/Desktop/apiproject/node_modules/google-trends-api/lib/resources/htmlParser.js:5:46)
at /Users/name/Desktop/apiproject/node_modules/google-trends-api/lib/utils/topRelated.js:25:11
at tryCatcher (/Users/name/Desktop/apiproject/node_modules/bluebird/js/release/util.js:16:23)
at Promise._settlePromiseFromHandler (/Users/name/Desktop/apiproject/node_modules/bluebird/js/release/promise.js:510:31)
at Promise._settlePromise (/Users/name/Desktop/apiproject/node_modules/bluebird/js/release/promise.js:567:18)
at Promise._settlePromise0 (/Users/name/Desktop/apiproject/node_modules/bluebird/js/release/promise.js:612:10)
at Promise._settlePromises (/Users/name/Desktop/apiproject/node_modules/bluebird/js/release/promise.js:691:18)
at Async._drainQueue (/Users/name/Desktop/apiproject/node_modules/bluebird/js/release/async.js:138:16)
at Async._drainQueues (/Users/name/Desktop/apiproject/node_modules/bluebird/js/release/async.js:148:10)
at Immediate.Async.drainQueues (/Users/name/Desktop/apiproject/node_modules/bluebird/js/release/async.js:17:14)
at runCallback (timers.js:574:20)
at tryOnImmediate (timers.js:554:5)
at processImmediate [as _immediateCallback] (timers.js:533:5) ]

Not getting how to have api functioning with 'require'

I know this is an ignorance of mine and not an issue with the code. Firstly, I'd like to thank the author of this repository.

Could you explain how do I get this api functioning on my application? I know it all starts with:

var googleTrends = require('google-trends-api')
But that's exactly where I am failing to succeed at using the plugin. :( Now I know it's dumb, lol but please have mercy on me.

I've downloaded requirejs from http://requirejs.org/ and included it on my page. But when I manage to require the plugin, it doesn't recognize "module.exports" or the "_dirname" variable. I don't quite understand this require Javascript solution.

Thanks

Searching by category

Hey There,

I was wondering if there's a way to choose the category, I see you specified it to 0 (cat: 0) in your code and changing it doesn't seem to affect the results.

is there any way to make the category a parameter and make it work ?

Thanks

Multiple Keyword searches (comparison)

Hello,

Since the version change (and the documentation change), It's unclear how to query multiple keywords. Previously it was a keywords parameter which could be an array. Now it's singular keyword, and it doesn't seem to support an array.

I have tried using a comma separated list but just get empty results, i.e.

{"default":{"timelineData":[],"averages":[]}}

I tried the following;

googleTrends.interestOverTime({keyword: 'toast, strawberry'})
.then(function(results){
        console.log('These results are awesome', results);
        callback(null, results);
})
.catch(function(err){
        callback(err, 'Oh no there was an error');
});

also tried..

googleTrends.interestOverTime({keyword: ['toast', 'strawberry']})

Essentially I'm looking for something like this;

image

Have I missed something?

Error in version 4.0.0

Hello!

Just running the example code;

var googleTrends = require('google-trends-api');

googleTrends.interestOverTime({keyword: 'Valentines Day'})
.then(function(results){
  console.log(results);
})
.catch(function(err){
  console.error(err);
});

Getting the following error;

TypeError: Cannot read property 'toUpperCase' of undefined
    at /google-trends/node_modules/google-trends-api/lib/google-trends-api.min.js:1:3609
    at Array.some (native)
    at s (/google-trends/node_modules/google-trends-api/lib/google-trends-api.min.js:1:3580)
    at u (/google-trends/node_modules/google-trends-api/lib/google-trends-api.min.js:1:3869)
    at Object.interestOverTime (/google-trends/node_modules/google-trends-api/lib/google-trends-api.min.js:1:2235)
    at Object.<anonymous> (/google-trends/test.js:3:14)
    at Module._compile (module.js:556:32)
    at Object.Module._extensions..js (module.js:565:10)
    at Module.load (module.js:473:32)
    at tryModuleLoad (module.js:432:12)
    at Function.Module._load (module.js:424:3)
    at Module.runMain (module.js:590:10)
    at run (bootstrap_node.js:394:7)
    at startup (bootstrap_node.js:149:9)
    at bootstrap_node.js:509:3

I'm assuming it's something to do with;

image

JSON Parse error in one of your examples

When I run

googleTrends.interestOverTime({keyword: 'Women\'s march'})
.then(function(results){
  console.log('These results are awesome', results);
})
.catch(function(err){
  console.error('Oh no there was an error', err);
});

This happens.

Oh no there was an error SyntaxError: Unexpected token L in JSON at position 0
    at JSON.parse (<anonymous>)
    at /Users/howonbyun/Desktop/work/adi/is-it-fire/node_modules/google-trends-api/lib/google-trends-api.min.js:146:22
    at process._tickCallback (internal/process/next_tick.js:103:7)

The endpoint is probably wrong or something. Has anyone used this successfully?

Regions / Country breakdowns

Hello again :)

I'm currently looking into how we might do requests using a specific region / city / county rather than the country. For instance, being able to do "England" or "Scotland" rather than limited to just "UK".

Not sure if anyone has managed to do this yet?

Usage with Angular2

Hi this is a great project any chance you can post an example using angular-cli? (angular2)?

relatedQueries/relatedTopics : Top and Rising

thank you for your work and your for your package.

But I have question about the results of your relatedQueries() and relatedTopics() functions. I think they don't return the top and the rising status.

Am i false ?

best regards

Fred

Reason for removal of hotTrendsDetail()?

Hi, I was just wondering as to why the hotTrendsDetail method was removed and if there is a replacement. Is there a way to get the most popular google searches in the new version of the module?

Thanks

Having CORS issues with methods provided

I am testing your api locally in Reactjs. Since your methods don't require a header, I am unable to bypass the origin allowance issues. Is there a way to bypass CORS issues with this API?

Get trends by day

When I choose a large time frame, I get the data per week or month and if I get a small time frame, I get the data per day. Is it possible to get the data of every days on a large time frame?

Open Source License?

Hi Patrick,

I've been searching your repo for a LICENSE file that describes the license that you released your project under. I can't find one, which implies that that the code is public, but not free to use. We'd like to use google-trends-api in a sample that we are working on, but we need to have an OSS license (MIT for preference) that we can show our legal team before we can use it.

Chuck Bigham
Microsoft Office

Can we add shouldIncludeTime optional ?

Hey,

Can we add shouldIncludeTime optional just like that;

utilities.js
let shouldIncludeTime;

  if (obj.shouldIncludeTime) {
    shouldIncludeTime = isLessThan7Days(obj.startTime, obj.endTime);
  }

Sample usage;

googleTrends.interestByRegion({
  keyword: 'Donald Trump',
  startTime: new Date('2017-02-01'),
  endTime: new Date('2017-02-03'),
  resolution: 'CITY',
  shouldIncludeTime: false
})

In that way we can get only daily data from google trends. Even less than 7 days.

Possible bug in parseJSON function

There might be a possible bug in parseJSON function. https://github.com/pat310/google-trends-api/blob/master/src/resources/htmlParser.js#L38

  1. When querying with multiple keywords, the data returned by this function is wrong and doesn't match the data returned by Google Trends call made in browser. So there's a bug in this function.
  2. Why are you using Regex? I think parsing the JSON inside the function google.visualization.Query.setResponse is much safer and correct. This way you can easily separate the data for multiple keywords into their own array just by looping through the response once.

I'd like to make a fix to this by rewriting the parseJSON function to use the JSON parsing idea I have in point 2.

Would you like to accept a merge ?

Quota limit?

Whenever I try using trendData(); I get an error response from Google saying my quota limit is exceeded though it was just a few tries before. Any workaround?

Error 400

Is this still working? I recieved an Error 400 when querying the api! JW thanks!

Not getting data for hourly trends.

Hi,
I saw this api, and i love it but their is one problem in your example how to get data for every minute is not working for me. If i try i get only empties arrays and and objects.

Thx

Timeout / Throttling issues

Hello again :)

This isn't really an issue with the library but recently (in the last few days), I noticed that the API requests are taking a lot longer than they used to. Sometimes taking as long as 20 something seconds.

I'm curious if it's something with my set up (which hasn't changed in about a year), or if anyone else is getting the same problem. I didn't know if Google have implemented any sort of throttling or anything. My solution has just been to increase the timeout of my scripts.

Hopefully, this is just a temporary issue with Google's service.

Proxy Option for Requests

Hey,

sometimes when you are behind a company proxy you will need the proxy option of request.
Is it possible, that you can provide this?

Thanks

change server port 8080

Hi,
I would like to change the default port that is used by this script (8080). How can i achieve this ?
Thanks.

Error when comparison contains both Search terms and Topics

The error is "TypeError: Cannot read property 'requestOptions' of undefined"

This stems from the handling of`the parsed results.

The reason is because in Google's UI, and correspondingly in widgets JSON, there's a message at the top: "Note: This comparison contains both Search terms and Topics, which are measured differently."

In JSON, it looks like this

[
  {
    "text": {
      "text": "This comparison contains both Search terms and Topics, which are measured differently"
    },
    "url": "https://support.google.com/trends/answer/4359550",
    "id": "topics_note",
    "type": "fe_text",
    "title": "",
    "template": "fe_explore_note",
    "embedTemplate": "fe_embed",
    "version": "1",
    "isLong": true,
    "isCurated": false
  },
  {
    "request": {
      "time": "2016-08-26 2017-08-26",
      "resolution": "WEEK",
      "locale": "en-US",
      "comparisonItem": [
        {
          "geo": {},
          "complexKeywordsRestriction": {
            "keyword": [
              {
                "type": "ENTITY",
                "value": "/m/0128447t"
              }
            ]
          }
        },
...

As a result, the rest of the widgets get shifted by 1, so pos needs to be incremented as well.

A possible fix is to modify this try caluse of parseResults() to

var widgets = JSON.parse(e.slice(4)).widgets;
if (!widgets[0].request) { widgets.shift(); }
return widgets;

Quota defeating / Authentication

Hello!

I've been wondering about overcoming the Quota problem. Currently, I cannot really run any of the calls without getting the Quota error - the first request I did today got the error. Then sometimes it works, other times it doesn't.

I read some suggestions by others about overcoming this by doing a request to login and grabbing the cookies, then sending those cookies with the request to the API so that it thinks you're authenticated and the quota is not so tight.

Not sure if anyone has tried this yet or found other ways to overcome the quota errors?

After grabbing my cookies from the browser after doing a search on google trends, I added them to the trendData.js request and it does actually appear to work, something like this allows me to make more regular requests;

( I have obfuscated the real cookie values )

rp( {
	uri: 'http://www.google.com/trends/fetchComponent?q="' + keyword + '"&cid=TIMESERIES_GRAPH_0&export=3',
	headers: {
		'Cookie': 'APISID=phZcBBd_oF_clAao/A2biC9KLw1Wk42F4H; GMAIL_RTT=223; HSID=AvCAPi1_gcLNPHp04; NID=90\=ljp9bPedFIvbHjyJu_ASSrzAyOjG8bql-141rlIlMUAFUl2whg2O7g6u8Fa0_I5Nf3WteTzfPF4UEp1K5BZw_FLqRXrpdICasdbkRT24zGGkdJHloBLmNZ55hJb2EgUtfsglxlevfPTIeM5bSZ0SmQejORetaXY_yWUvLxQ5NgsxFjMw8eBuqFYruG3aOMhK4jCrc2p8evYPwLMU5t5z1YqdjvBsJw0pWHTHpM7WWWqHhEVvPgZh8SwvAdCTMidd4Q9TTa3bX77lA8hG_kvcaXGApb1ppelSHCE607viCgNYy4pBHAMYypWW9cgX_WxwOmhzvbSjNn21gJZw6TUkadGhEt8vWYjbJUW7q; SAPISID=cZpNlAneFfMDfB3FLx/AB-QxJFQYeWxEY6zB; SID=7gOUsm_siHAB7zmta3cPjuZM-Nos7Ok4pEekdyB_DPpWH3CspzMf4fxnJ7QoWelTrapcMg.; SSID=ASVarA9Iip_lMFg-w;'
			}
});

How reliable this method will be, I'm not sure. Regardless I think something will need to be built in to any app using this to detect the quota and retry later.

Typo in the readme

I believe the googleTrends.categoryTopCharts example should be something like this:

googleTrends.categoryTopCharts({category: 'actors', geo: 'US', date: '201601'})
.then(function(results){
...

'https' module issue

I want to use google-trends-api in React Native.
I tried to do that but it returned an error saying:

err

I installed 'https' module in my project folder and in node_module folders but it didn't help.
I thought it would be because of only RN's problem so I tested it out on the webpage in React
and I checked it worked on the web in React! but why not React Native?
I also guess I made my project with 'create-react-native-app' so possibly that would be it.

node.js : 8.9.4
npm : 4.6.1
google-trends-api : 4.3.0
https : 1.0.0
react : 16.0.0
react-native : 0.50.3

Downloading Topic information

For interest over time, we can pass in search terms , start and end dates, Geo using syntax below.

How do you pass in a topic?

googleTrends.interestOverTime({keyword: string, startTime: Date, endTime: Date, geo: string}, cbFunc)

Requires an object as the first parameter with the following keys:

keyword - required - type string or array - the search term(s) of interest
startTime - optional - type Date object - the start of the time range of interest (defaults to new Date('2004-01-01') if not supplied)
endTime - optional - type Date object - the end of the time range of interest (defaults to new Date(Date.now()) if not supplied)
geo - optional - type string - geocode for a country, region, or DMA depending on the granularity required (defaults to worldwide). For example, geo: 'US-CA-800' will target the Bakersfield, California, United States or geo: 'US' will just target the US.
hl - optional - type string - preferred language code for results (defaults to english)

Category names

Hello again,

I'm wondering about the category names, Is there a list of the exact values that are supported, or could we make it so that you can specify a category id (i.e. "Food & Drink" is category 71, and I wouldn't know how to supply this with the api, "food and drink", "food & drink", "food&drink" etc?.

On an aside, I'm also thinking, is it possible to supply the 'type' of search term? i.e. the difference between;

image

and

image

Which seems to be separate to the 'category'.

Problem with United Kingdom (UK / GB) Country Codes?

I've had issues with the abbreviations for the United Kingdom.

Both googleTrends.hotTrendsDetail("UK") and googleTrends.hotTrendsDetail("GB") were returning errors.

I checked the countryCodes file and it seems there is an inconsistency in denominations:

  • mapToNumber uses UK
  • mapToAbbreviation uses GB
  • mapToDomain uses UK

I've had success changing everything to UK or to GB, but there needs to be consistency.

Perhaps ideally both codes should be accepted.

Would love to fix this myself but I'm not quite at that level of skill yet. If anyone needs a hot fix however, just know that you can get around it by tinkering the countryCodes file.

New Error - 302 Moved / CAPTCHA

Hello again!

Now, this was working a treat about an hour ago, but now I'm getting errors because google is no longer returning results, it's returning a 302 (if I log the raw output I get an html page, so the JSON is failing to parse and then the module is erroring - should check that it's valid json maybe?).

<HTML><HEAD><meta http-equiv="content-type" content="text/html;charset=utf-8">
<TITLE>302 Moved</TITLE></HEAD><BODY>
<H1>302 Moved</H1>
The document has moved
<A HREF="https://ipv4.google.com/sorry/index?continue=https://www.google.com/trends/api/explore%3Fhl%3Den-US%26req%3D%257B%2522comparisonItem%2522%253A%255B%257B%2522keyword%2522%253A%2522Women%27s%2520march%2522%252C%2522hl%2522%253A%2522en-US%2522%252C%2522endTime%2522%253A%25222017-02-15T10%253A39%253A43.469Z%2522%252C%2522startTime%2522%253A%25222004-01-01T00%253A00%253A00.000Z%2522%252C%2522time%2522%253A%25222004-01-1%25202017-02-15%2522%257D%255D%252C%2522cat%2522%253A0%257D%26tz%3D300&amp;hl=en-US&amp;q=EgRSmJyrGO_fkMUFIhkA8aeDS4wL63ml_8QWbc51FLsxqzmXnxSDMgFj">here</A>.
</BODY></HTML>

This links over to a CAPTCHA like this;

image

Looks like we're going to have to implement the authentication and cookie sending afterall!

Error when adding geo to region query

I've been pulling my hair out about this, so hopefully this helps someone else out haha.

When using 4.2.1, if you add a geo field to an interest by region query, you'll get an error. I downgraded to 4.1.0 like I had in my other project and the error no longer occurs and you get the expected response.

Params:
keywords: ['Apple, Dell, Lenovo'],
resolution: 'STATE',
geo: 'US',
startTime,
endTime

{ message: 'Available widgets does not contain selected api type', requestBody: ')]}\'\n{"widgets":[{"request":{"time":"2017-08-06 2017-09-05","resolution":"DAY","locale":"en-US","comparisonItem":[{"geo":{"country":"US"},"complexKeywordsRestriction":{"keyword":[{"type":"BROAD","value":"Dell"}]}},{"geo":{"country":"US"},"complexKeywordsRestriction":{"keyword":[{"type":"BROAD","value":"Lenovo"}]}},{"geo":{"country":"US"},"complexKeywordsRestriction":{"keyword":[{"type":"BROAD","value":"Apple"}]}}],"requestOptions":{"property":"","backend":"IZG","category":0}},"lineAnnotationText":"Search interest","bullets":[{"text":"Dell"},{"text":"Lenovo"},{"text":"Apple"}],"showLegend":false,"showAverages":true,"helpDialog":{"title":"Interest over time","content":"Numbers represent search interest relative to the highest point on the chart for the given region and time. A value of 100 is the peak popularity for the term. A value of 50 means that the term is half as popular. Likewise a score of 0 means the term was less than 1% as popular as the peak."},"token":"APP6_UEAAAAAWbDDbIM2RzHuiv6T5tOW8JepdJT2xNOx","id":"TIMESERIES","type":"fe_line_chart","title":"Interest over time","template":"fe","embedTemplate":"fe_embed","version":"1","isLong":true,"isCurated":false},{"request":{"geo":{"country":"US"},"comparisonItem":[{"time":"2017-08-06 2017-09-05","complexKeywordsRestriction":{"keyword":[{"type":"BROAD","value":"Dell"}]}},{"time":"2017-08-06 2017-09-05","complexKeywordsRestriction":{"keyword":[{"type":"BROAD","value":"Lenovo"}]}},{"time":"2017-08-06 2017-09-05","complexKeywordsRestriction":{"keyword":[{"type":"BROAD","value":"Apple"}]}}],"resolution":"REGION","locale":"en-US","requestOptions":{"property":"","backend":"IZG","category":0}},"geo":"US","resolution":"provinces","searchInterestLabel":"Search interest","displayMode":"regions","showLegend":false,"helpDialog":{"title":"Interest by subregion","content":"See which term ranked highest in each region during the specified time frame. Values are scaled from 0 to 100, where 100 is the region with peak popularity, a value of 50 is the region where the term is half as popular, and a value of 0 means that term was less than 1% as popular as the peak."},"bullets":[{"value":"Dell","color":"PALETTE_COLOR_1"},{"value":"Lenovo","color":"PALETTE_COLOR_2"},{"value":"Apple","color":"PALETTE_COLOR_3"}],"token":"APP6_UEAAAAAWbDDbJd-1wv45UK9aeSmjHDehgtDHXQx","id":"GEO_MAP","type":"fe_geo_color_chart","title":"Interest by subregion","template":"fe","embedTemplate":"fe_embed","version":"2","isLong":true,"isCurated":false},{"text":{"text":"Dell"},"id":"TITLE_0","type":"fe_text","title":"","template":"fe_explore","embedTemplate":"fe_embed","version":"1","isLong":true,"isCurated":false},{"request":{"geo":{"country":"US"},"comparisonItem":[{"time":"2017-08-06 2017-09-05","complexKeywordsRestriction":{"keyword":[{"type":"BROAD","value":"Dell"}]}}],"resolution":"REGION","locale":"en-US","requestOptions":{"property":"","backend":"IZG","category":0}},"geo":"US","resolution":"provinces","searchInterestLabel":"Search interest","displayMode":"regions","helpDialog":{"title":"Interest by subregion","content":"See in which location your term was most popular during the specified time frame. Values are calculated on a scale from 0 to 100, where 100 is the location with the most popularity as a fraction of total searches in that location, a value of 50 indicates a location which is half as popular, and a value of 0 indicates a location where the term was less than 1% as popular as the peak. \\u003cp\\u003e\\u003cp\\u003e \\u003cb\\u003eNote:\\u003c/b\\u003e A higher value means a higher proportion of all queries, not a higher absolute query count. So a tiny country where 80% of the queries are for \\"bananas\\" will get twice the score of a giant country where only 40% of the queries are for \\"bananas\\".","url":"https://support.google.com/trends/answer/4355212"},"color":"PALETTE_COLOR_1","index":0,"bullet":"Dell","token":"APP6_UEAAAAAWbDDbGvVQcVQq51Vlkj4R-89YJYGxfHF","id":"GEO_MAP_0","type":"fe_geo_chart_explore","title":"Interest by subregion","template":"fe","embedTemplate":"fe_embed","version":"1","isLong":false,"isCurated":false},{"request":{"restriction":{"geo":{"country":"US"},"time":"2017-08-06 2017-09-05","complexKeywordsRestriction":{"keyword":[{"type":"BROAD","value":"Dell"}]}},"keywordType":"QUERY","metric":["TOP","RISING"],"trendinessSettings":{"compareTime":"2017-07-06 2017-08-05"},"requestOptions":{"property":"","backend":"IZG","category":0},"language":"en"},"helpDialog":{"title":"Related queries","content":"Users searching for your term also searched for these queries. You can sort by the following metrics: \\u003cp\\u003e* \\u003cb\\u003eTop\\u003c/b\\u003e - The most popular search queries. Scoring is on a relative scale where a value of 100 is the most commonly searched query, 50 is a query searched half as often, and a value of 0 is a query searched for less than 1% as often as the most popular query. \\u003cp\\u003e* \\u003cb\\u003eRising\\u003c/b\\u003e - Queries with the biggest increase in search frequency since the last time period. Results marked \\"Breakout\\" had a tremendous increase, probably because these queries are new and had few (if any) prior searches.","url":"https://support.google.com/trends/answer/4355000"},"color":"PALETTE_COLOR_1","keywordName":"Dell","token":"APP6_UEAAAAAWbDDbPfY4X2CiKvxmFP0NTZH5lrYJFqA","id":"RELATED_QUERIES_0","type":"fe_related_searches","title":"Related queries","template":"fe","embedTemplate":"fe_embed","version":"1","isLong":false,"isCurated":false},{"text":{"text":"Lenovo"},"id":"TITLE_1","type":"fe_text","title":"","template":"fe_explore","embedTemplate":"fe_embed","version":"1","isLong":true,"isCurated":false},{"request":{"geo":{"country":"US"},"comparisonItem":[{"time":"2017-08-06 2017-09-05","complexKeywordsRestriction":{"keyword":[{"type":"BROAD","value":"Lenovo"}]}}],"resolution":"REGION","locale":"en-US","requestOptions":{"property":"","backend":"IZG","category":0}},"geo":"US","resolution":"provinces","searchInterestLabel":"Search interest","displayMode":"regions","helpDialog":{"title":"Interest by subregion","content":"See in which location your term was most popular during the specified time frame. Values are calculated on a scale from 0 to 100, where 100 is the location with the most popularity as a fraction of total searches in that location, a value of 50 indicates a location which is half as popular, and a value of 0 indicates a location where the term was less than 1% as popular as the peak. \\u003cp\\u003e\\u003cp\\u003e \\u003cb\\u003eNote:\\u003c/b\\u003e A higher value means a higher proportion of all queries, not a higher absolute query count. So a tiny country where 80% of the queries are for \\"bananas\\" will get twice the score of a giant country where only 40% of the queries are for \\"bananas\\".","url":"https://support.google.com/trends/answer/4355212"},"color":"PALETTE_COLOR_2","index":1,"bullet":"Lenovo","token":"APP6_UEAAAAAWbDDbDIJ4rjDa5BvsflSwsUmM2oZyUVP","id":"GEO_MAP_1","type":"fe_geo_chart_explore","title":"Interest by subregion","template":"fe","embedTemplate":"fe_embed","version":"1","isLong":false,"isCurated":false},{"request":{"restriction":{"geo":{"country":"US"},"time":"2017-08-06 2017-09-05","complexKeywordsRestriction":{"keyword":[{"type":"BROAD","value":"Lenovo"}]}},"keywordType":"QUERY","metric":["TOP","RISING"],"trendinessSettings":{"compareTime":"2017-07-06 2017-08-05"},"requestOptions":{"property":"","backend":"IZG","category":0},"language":"en"},"helpDialog":{"title":"Related queries","content":"Users searching for your term also searched for these queries. You can sort by the following metrics: \\u003cp\\u003e* \\u003cb\\u003eTop\\u003c/b\\u003e - The most popular search queries. Scoring is on a relative scale where a value of 100 is the most commonly searched query, 50 is a query searched half as often, and a value of 0 is a query searched for less than 1% as often as the most popular query. \\u003cp\\u003e* \\u003cb\\u003eRising\\u003c/b\\u003e - Queries with the biggest increase in search frequency since the last time period. Results marked \\"Breakout\\" had a tremendous increase, probably because these queries are new and had few (if any) prior searches.","url":"https://support.google.com/trends/answer/4355000"},"color":"PALETTE_COLOR_2","keywordName":"Lenovo","token":"APP6_UEAAAAAWbDDbMvLoEl8Vula9Nq93Z9O53VuxyZL","id":"RELATED_QUERIES_1","type":"fe_related_searches","title":"Related queries","template":"fe","embedTemplate":"fe_embed","version":"1","isLong":false,"isCurated":false},{"text":{"text":"Apple"},"id":"TITLE_2","type":"fe_text","title":"","template":"fe_explore","embedTemplate":"fe_embed","version":"1","isLong":true,"isCurated":false},{"request":{"geo":{"country":"US"},"comparisonItem":[{"time":"2017-08-06 2017-09-05","complexKeywordsRestriction":{"keyword":[{"type":"BROAD","value":"Apple"}]}}],"resolution":"REGION","locale":"en-US","requestOptions":{"property":"","backend":"IZG","category":0}},"geo":"US","resolution":"provinces","searchInterestLabel":"Search interest","displayMode":"regions","helpDialog":{"title":"Interest by subregion","content":"See in which location your term was most popular during the specified time frame. Values are calculated on a scale from 0 to 100, where 100 is the location with the most popularity as a fraction of total searches in that location, a value of 50 indicates a location which is half as popular, and a value of 0 indicates a location where the term was less than 1% as popular as the peak. \\u003cp\\u003e\\u003cp\\u003e \\u003cb\\u003eNote:\\u003c/b\\u003e A higher value means a higher proportion of all queries, not a higher absolute query count. So a tiny country where 80% of the queries are for \\"bananas\\" will get twice the score of a giant country where only 40% of the queries are for \\"bananas\\".","url":"https://support.google.com/trends/answer/4355212"},"color":"PALETTE_COLOR_3","index":2,"bullet":"Apple","token":"APP6_UEAAAAAWbDDbNy0ioc1H3cN-yKAe9w4qU4qljlZ","id":"GEO_MAP_2","type":"fe_geo_chart_explore","title":"Interest by subregion","template":"fe","embedTemplate":"fe_embed","version":"1","isLong":false,"isCurated":false},{"request":{"restriction":{"geo":{"country":"US"},"time":"2017-08-06 2017-09-05","complexKeywordsRestriction":{"keyword":[{"type":"BROAD","value":"Apple"}]}},"keywordType":"QUERY","metric":["TOP","RISING"],"trendinessSettings":{"compareTime":"2017-07-06 2017-08-05"},"requestOptions":{"property":"","backend":"IZG","category":0},"language":"en"},"helpDialog":{"title":"Related queries","content":"Users searching for your term also searched for these queries. You can sort by the following metrics: \\u003cp\\u003e* \\u003cb\\u003eTop\\u003c/b\\u003e - The most popular search queries. Scoring is on a relative scale where a value of 100 is the most commonly searched query, 50 is a query searched half as often, and a value of 0 is a query searched for less than 1% as often as the most popular query. \\u003cp\\u003e* \\u003cb\\u003eRising\\u003c/b\\u003e - Queries with the biggest increase in search frequency since the last time period. Results marked \\"Breakout\\" had a tremendous increase, probably because these queries are new and had few (if any) prior searches.","url":"https://support.google.com/trends/answer/4355000"},"color":"PALETTE_COLOR_3","keywordName":"Apple","token":"APP6_UEAAAAAWbDDbJeiZ14aIjNtCowwwvSHLz-6AwWC","id":"RELATED_QUERIES_2","type":"fe_related_searches","title":"Related queries","template":"fe","embedTemplate":"fe_embed","version":"1","isLong":false,"isCurated":false}],"keywords":[{"keyword":"Dell","name":"Dell","type":"Search term"},{"keyword":"Lenovo","name":"Lenovo","type":"Search term"},{"keyword":"Apple","name":"Apple","type":"Search term"}],"timeRanges":["8/6/17 - 9/5/17","8/6/17 - 9/5/17","8/6/17 - 9/5/17"],"examples":[],"shareText":"Explore search interest for Dell, Lenovo, Apple by time, location and popularity on Google Trends"}' }

Unexpected token L in JSON at position 0

I know this issue has been resolved in the past but it seems it has resurfaced for me at least. This library was working a few weeks ago (@Version 4.4.0) however now with the latest version I can't make any calls with the same code. It seems that Google is flagging these calls as 'automated' and unusual traffic. Any tips on getting past this? I'm signed into google and have tried this using both Chrome and Firefox.

Using the latest version of node (9.6.1) and npm (5.6.0)

SPECIFIC ERROR BELOW:
{ SyntaxError: Unexpected token L in JSON at position 0
at JSON.parse ()
at a (/Users/MLegocki/FullStack/Projects/CryptoTrends/node_modules/google-trends-api/lib/google-trends-api.min.js:1:2976)
at /Users/MLegocki/FullStack/Projects/CryptoTrends/node_modules/google-trends-api/lib/google-trends-api.min.js:1:3887
at
at process._tickCallback (internal/process/next_tick.js:160:7)
requestBody: '\n<TITLE>302 Moved</TITLE>\n

302 Moved

\nThe document has moved\nhere.\r\n\r\n' }

Usage with sails.js

I'm trying to use this api with sails.js, but the response return the trends response data.
The controller function looks like this:

googleTrends.interestOverTime({keyword: [req.param('keyword')]})
		.then(function(results){
		 	return res.send(results);
		})
		.catch(function(err){
		  return res.json(err);
		});

Returns this:

image

Is there any way to return the data as json object?

topRelated call must have a timePeriod object

In the README.md, it's says that it's optionnal, but i got this:

Error: timePeriod must be an object of type {type: enum, value: number}
at module.exports (/Users/name/Desktop/apiproject/node_modules/google-trends-api/lib/resources/timePeriodConverter.js:7:105)
at parseArguments (/Users/name/Desktop/apiproject/node_modules/google-trends-api/lib/resources/callbacks.js:37:25)
at Object.request [as topRelated] (/Users/name/Desktop/apiproject/node_modules/google-trends-api/lib/utils/topRelated.js:9:12)
at /Users/name/Desktop/apiproject/src/entities/GoogleTrends.js:19:20
at GoogleTrends.topRelated (/Users/name/Desktop/apiproject/src/entities/GoogleTrends.js:18:12)
at /Users/name/Desktop/apiproject/src/server.js:38:16
at Layer.handle [as handle_request] (/Users/name/Desktop/apiproject/node_modules/express/lib/router/layer.js:95:5)
at next (/Users/name/Desktop/apiproject/node_modules/express/lib/router/route.js:131:13)
at Route.dispatch (/Users/name/Desktop/apiproject/node_modules/express/lib/router/route.js:112:3)
at Layer.handle [as handle_request] (/Users/name/Desktop/apiproject/node_modules/express/lib/router/layer.js:95:5)
at /Users/name/Desktop/apiproject/node_modules/express/lib/router/index.js:277:22
at Function.process_params (/Users/name/Desktop/apiproject/node_modules/express/lib/router/index.js:330:12)
at next (/Users/name/Desktop/apiproject/node_modules/express/lib/router/index.js:271:10)
at jsonParser (/Users/name/Desktop/apiproject/node_modules/body-parser/lib/types/json.js:103:7)
at Layer.handle [as handle_request] (/Users/name/Desktop/apiproject/node_modules/express/lib/router/layer.js:95:5)
at trim_prefix (/Users/name/Desktop/apiproject/node_modules/express/lib/router/index.js:312:13)
at /Users/name/Desktop/apiproject/node_modules/express/lib/router/index.js:280:7
at Function.process_params (/Users/name/Desktop/apiproject/node_modules/express/lib/router/index.js:330:12)
at next (/Users/name/Desktop/apiproject/node_modules/express/lib/router/index.js:271:10)
at expressInit (/Users/name/Desktop/apiproject/node_modules/express/lib/middleware/init.js:33:5)
at Layer.handle [as handle_request] (/Users/name/Desktop/apiproject/node_modules/express/lib/router/layer.js:95:5)
at trim_prefix (/Users/name/Desktop/apiproject/node_modules/express/lib/router/index.js:312:13)

interestOverTime not working on shorter time ranges.

I would like to test the method interestOverTime with a small time scale such as 4 hours, however, no data is being returned. Is this intended? An example is listed which is this:

googleTrends.interestOverTime({keyword: 'Valentines Day', startTime: new Date(Date.now() - (4 * 60 * 60 * 1000))}, function(err, results) {
  if (err) console.log('oh no error!', err);
  else console.log(results);
});

And running that, I get the following:

{"default":{"timelineData":[],"averages":[]}}

I get no data at all until I move it out until > 40 hours ago. Is it just me?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.