Google Trend API

In this blog post with the power of Google Trend's API we create a search app. Google Trends is a website by Google that analyzes the popularity of top search queries in Google Search across various regions and languages. The website uses graphs to compare the search volume of different queries over time.

Mr. Cohen
November 10, 20204 min read

Source Code: https://github.com/y0d32/googleTrend

Why Google Trend API?

Google Trends is a website by Google that analyzes the popularity of top search queries in Google Search across various regions and languages. The website uses graphs to compare the search volume of different queries over time.

Let's Get Started!

In the first part we have the modules that we imported to create the script. They are well known in the data analytics area and we have modules such as pandas, matplotlib and seaborn. Pytrends helps us to log in to the Google api. The rest of the modules are useful in creating the script to read data about the operating system (os, sys) Argparse is important to write parameters of the script, which the user enters as arguments with the values ​​required by them.

from pytrends.request import TrendReq
from datetime import date
import matplotlib.pyplot as plt
import seaborn as sns
import pandas as pd
import datetime
import sys
import os
import argparse
import pathlib
import uuid

The 2 parameters are -q (the word for query, which we want to search in the Google database) and -c (country, in Iso format for 2 characters eg RO for Romania, US for America, UK for England etc ). As a timeframe the search starts from 1.01.2020 until now, when the user runs the script.

ap = argparse.ArgumentParser()
ap.add_argument("-q", "--query", required=True, help="insert your word")

ap.add_argument("-c", "--country", required=False, help="country to search on")

args = ap.parse_args()

key_word = args.query
country = args.country

The query itself is done through these lines of code.

pytrends = TrendReq(hl='en-US', tz=360)
pytrends.build_payload(
    [key_word], cat=0, timeframe=day,  gprop='', geo=country)
df = pytrends.interest_over_time()

Project Structure

The answer received from google is saved in a data frame which we will later convert into a graph, using the matplotlib ==> pyplot module. Like any graphic, it needs a label for the X and Y axis and a dynamic title depending on the query and the searched word.

df = pytrends.interest_over_time()

unique_filename = str(uuid.uuid4())

result = '%s-%s-%s_%s' % (date.year, date.month, date.day, unique_filename)
sns.set()
df['timestamp'] = pd.to_datetime(df.index)
sns.lineplot(df['timestamp'], df[key_word])

if country is None:
    plt.title("The global trend of " + key_word)
    name =   key_word + result+ ".png"
else:
    plt.title("The trend of  " + key_word + "  in " + country)
    name =   country + key_word + result + ".png"


plt.ylabel("Number of Searches of " + key_word)
plt.xlabel("TimeFrame")

Components

Before displaying the plot, it is a good practice to save it so that the name is unique. The save is made in the same folder where you run the script, and at the end the created chart is shown

filepath = pathlib.Path(__file__).resolve().parent

path = os.path.join(filepath, name)

plt.savefig(path)
plt.show()

Now the entire code will look like this:

file.py

from datetime import date
import matplotlib.pyplot as plt
import seaborn as sns
import pandas as pd
import datetime
import sys
import os
import argparse
import pathlib
import uuid

date = datetime.datetime.now()

ap = argparse.ArgumentParser()
ap.add_argument("-q", "--query", required=True, help="insert your word")

ap.add_argument("-c", "--country", required=False, help="country to search on")

args = ap.parse_args()

key_word = args.query
country = args.country
day = '2020-01-01 ' + datetime.datetime.today().strftime('%Y-%m-%d')

pytrends = TrendReq(hl='en-US', tz=360)
pytrends.build_payload(
    [key_word], cat=0, timeframe=day,  gprop='', geo=country)
df = pytrends.interest_over_time()

print(df.head())

unique_filename = str(uuid.uuid4())

result = '%s-%s-%s_%s' % (date.year, date.month, date.day, unique_filename)
sns.set()
df['timestamp'] = pd.to_datetime(df.index)
sns.lineplot(df['timestamp'], df[key_word])

if country is None:
    plt.title("The global trend of " + key_word)
    name =   key_word + result+ ".png"
else:
    plt.title("The trend of  " + key_word + "  in " + country)
    name =   country + key_word + result + ".png"


plt.ylabel("Number of Searches of " + key_word)
plt.xlabel("TimeFrame")


filepath = pathlib.Path(__file__).resolve().parent

path = os.path.join(filepath, name)

plt.savefig(path)
plt.show()

Images

trend trend trend trend

More videos

You can find more info on Youtube here

My Video