Pytrends Tutorial: How to Use the Google Trends API in Python

Last Updated on 29 April 2025

pytrends in python

Introduction

Google Trends is a free tool that shows what people are searching for across the web. However, manually checking trends can be time-consuming. That’s where Pytrends, the unofficial Google Trends API for Python, becomes incredibly useful.

In this complete Pytrends tutorial, you’ll learn how to use the Pytrends API to analyze keyword popularity, track search interest over time, and explore trending topics — all using Python.

Read also: What is Seaborn in Python? A Guide to Data Visualization

What is Pytrends?

Pytrends is a Python library that interacts with Google Trends and allows users to retrieve search interest data for specific keywords. It helps track keyword popularity, compare multiple terms, and analyze trends by region or category.

Using Pytrends, you can:

  • Monitor keyword popularity over time
  • Compare multiple search terms
  • Analyze trends by region or country
  • Retrieve related queries and rising trends
  • Get Google Autocomplete suggestions
  • Fetch daily trending search topics

Installation

Install Pytrends using the following command:

pip install pytrends

Initialize Pytrends API

First, import the necessary module and initialize the Pytrends API:

from pytrends.request import TrendReq

# Create a Pytrends request
pytrends = TrendReq(hl='en-US', tz=360)

Checking Interest Over Time

The function interest_over_time() retrieves the search interest data for specified keywords over a given time period.

How it works?

It fetches the relative search interest for each keyword over time. The values range from 0 to 100, where:

  • 100 represents peak search interest.
  • 50 means the search term is half as popular as at its peak.
  • 0 means insufficient data for that time period.

The function returns a Pandas DataFrame, where:

  • The index represents time (usually daily or weekly).
  • Each column represents a keyword.
  • An additional ‘isPartial’ column indicates whether the data is partial.
# Define keyword(s)
kw_list = ["Python", "Java"]

# Build payload
pytrends.build_payload(kw_list, timeframe='today 12-m')

# Get interest over time
data = pytrends.interest_over_time()
print(data.head())

Output

            Python  Java  isPartial
date                               
2024-01-28      95    61      False
2024-02-04      97    60      False
2024-02-11     100    66      False
2024-02-18      97    64      False
2024-02-25      96    63      False

Interest by Region

Regional interest can help you understand where a keyword is most popular. For example, if you’re checking the popularity of Python language, knowing which regions search for it the most can help with marketing or creating content.

Here’s an example that shows how to retrieve the regional interest for the keyword “Python” and filter it by the top regions:

pytrends.build_payload(["Python"], timeframe='today 12-m', geo='')
data = pytrends.interest_by_region()

# Sort the data to show the top 10 regions with the highest interest in Python
top_regions = data.sort_values(by="Python", ascending=False).head(10)

# Display the top 10 regions
print("Top 10 Regions Interested in Python:")
print(top_regions[['Python']])

Output

Top 10 Regions Interested in Python:
             Python
geoName            
China           100
Singapore        23
Israel           21
Hong Kong        18
India            16
Switzerland      15
South Korea      14
Tunisia          13
Taiwan           12
Russia           12

Key Details:

  • geo parameter: This can be used to specify a region or country. For example, geo='US' would fetch data for the entire United States, or geo='IN' for India.
  • timeframe parameter: Defines the period over which the data is collected, like today 12-m for the last 12 months or now 7-d for the past week.

Related Queries

The related_queries() function retrieves other related search queries for a specific keyword. This function provides valuable insights into what other topics or queries are being searched in relation to the keyword you’re searching.

It categorizes the results into top queries and rising queries:

  • Top related queries: These are the most popular related searches in the given timeframe.
  • Rising related queries: These are searches that have seen the most significant increase in interest over a recent period that indicates trending topics.
# Create a Pytrends request
from pytrends.request import TrendReq

pytrends = TrendReq(hl='en-US', tz=360)

# Specify the keyword
keyword = ['Google', 'Facebook']

# Build the request payload
pytrends.build_payload(kw_list=keyword)


try:
    # Retrieve related queries data with error handling
    related_queries = pytrends.related_queries()

    top_queries = related_queries[keyword].get('top')
    rising_queries = related_queries[keyword].get('rising')

    print("Top Related Queries:")
    print(top_queries.head() if top_queries is not None else "No data available")

    print("\nRising Related Queries:")
    print(rising_queries.head() if rising_queries is not None else "No data available")
except (KeyError, IndexError):
    print("No related queries found for", keyword)

Output

No related queries found for ['Google', 'Facebook']

Google Autocomplete Suggestions

Google Autocomplete provides search predictions based on what users commonly search for. With Pytrends, you can fetch these suggestions programmatically. This is very useful for SEO, content creation, and keyword research.

suggestions = pytrends.suggestions(keyword="Python")

# Display suggestions
for suggestion in suggestions:
    print(suggestion['title'], ":", suggestion['type'])

Output

Python : Programming language
Ishan Sharma : YouTuber
Python family : Snake
Python for Data Analysis: Data Wrangling with Pandas, NumPy, and Jupyter : Book by Wes McKinney
Python : Snake

Daily Trending Searches

Apart from analyzing specific keywords, Pytrends also allows us to fetch Google’s daily trending searches using the today_searches() function. This helps to identify what’s currently trending worldwide or in a specific country.

from pytrends.request import TrendReq
import re

# Create a Pytrends request
pytrends = TrendReq(hl='en-US', tz=360)

# Get today's trending searches
trending_searches = pytrends.today_searches()

# Extract search terms from URLs
def extract_search_term(url):
    match = re.search(r"q=([^&]+)", url)
    return match.group(1).replace("+", " ") if match else url

# Convert to a readable list
trending_topics = [extract_search_term(link) for link in trending_searches]

# Print the cleaned trending searches
print("Today's Trending Searches in India:")
for i, topic in enumerate(trending_topics, start=1):
    print(f"{i}. {topic}")

Output

Today's Trending Searches:
1. Benavidez vs Morrell
2. UNC vs Duke
3. Espanyol vs Real Madrid
4. Ken Martin
5. Celtics
6. Warriors
7. Senior Bowl 2025
8. Kestrel
9. NASCAR
10. Tennessee basketball
11. Bournemouth vs Liverpool
12. Lakers vs Knicks
13. Jey Uso
14. Pebble Beach
15. Serie del Caribe 2025
16. Twinless
17. Nuggets vs Hornets
18. Somalia

Fetching Trends for a Specific Country

You can also get country-specific trending searches by passing a country code to today_searches(). For example, to fetch trending searches in India (‘IN’):

trending_searches_india = pytrends.today_searches(pn='IN')
print(trending_searches_india.head())

Limitations of Using the Pytrends Library

While Pytrends is a powerful tool, it has some limitations:

  • Unofficial API: Pytrends is not an official Google API, so it may break if Google changes its trends service.
  • Rate Limiting: Google may block excessive requests if too many are sent in a short period.
  • No exact search volumes: The data provided by Google Trends is not raw search volume but a normalized value, from 0 – 100.
  • Limited Historical Data: Some historical data is not available for specific queries.
  • Geo-Specific Restrictions: Certain queries may not be available in all countries or regions.

Read also: Google Colab for Python: Advantages vs Disadvantages

Summary

If you want to use Google Trends for SEO, content planning, or market research, Pytrends is a great Python tool to help you. It lets you track keyword popularity, compare terms, explore related searches, and much more — all with just a few lines of code.

This tutorial gave you practical examples to start using Pytrends in your own projects.

Start using Pytrends today and turn search data into smart decisions.

Happy Searching!

Share your love
Subhankar Rakshit
Subhankar Rakshit

Hey there! I’m Subhankar Rakshit, the brains behind PySeek. I’m a Post Graduate in Computer Science. PySeek is where I channel my love for Python programming and share it with the world through engaging and informative blogs.

Articles: 215