Registry / http-networking / pytrends

pytrends

JSON →
library4.9.2pypypi✓ verified 26d ago

Pytrends is an unofficial Python library that provides a pseudo-API for Google Trends, allowing users to automate the downloading of search interest data. The current version, 4.9.2, was released in April 2023. Due to its unofficial nature, it does not adhere to a fixed release cadence but rather updates as needed to adapt to changes in Google's backend, which can frequently introduce breaking changes.

pip install pytrends
INSTALL
IMPORT
SIG · PYTRENDS
P
pytrends
http-networkingpythonv4.9.2
Install
8.8s avg
Import
1169ms
Disk
180MB
Pass rate
10/ 10
Env Coverage10 / 10
glibc
3.9–3.13
musl
3.9–3.13
Install & Compatibility
Where this runs
tested against v4.9.2 · pip install
no network on importno background threads
Install × environment matrix
Each cell = how many times install + import succeeded across repeated harness runs. Partial = flaky.
glibc = Debian/Ubuntu slim · musl = Alpine Linux
musl
py 3.10–3.95 runs
installs and imports cleanly · install 0.0s · import 1.228s · 179.9MB
glibc
py 3.10–3.95 runs
installs and imports cleanly · install 8.8s · import 1.110s · 172MB
180MB installed
● package 180MB
Code
Verified usage

Verified import paths — ran on the pinned version, not inferred.

TrendReq
✓ from pytrends.request import TrendReq

This quickstart demonstrates how to initialize the `TrendReq` object, build a search payload for multiple keywords, and retrieve 'Interest Over Time' and 'Interest by Region' data from Google Trends. The data is returned as pandas DataFrames. Note the `tz` parameter for timezone offset, where '360' represents UTC-6 (e.g., US Central Standard Time) and not '-360'.

from pytrends.request import TrendReq import pandas as pd # Initialize pytrends object # hl: host language, tz: timezone offset (e.g., 360 for US CST, NOT -360) pytrends = TrendReq(hl='en-US', tz=360) # Define keyword list kw_list = ["Python programming", "Data Science"] # Build payload for the request # timeframe: e.g., 'today 5-y' for last 5 years pytrends.build_payload(kw_list, cat=0, timeframe='today 5-y', geo='US', gprop='') # Get Interest Over Time data interest_over_time_df = pytrends.interest_over_time() # Print the first few rows of the DataFrame print("Interest Over Time (first 5 rows):") print(interest_over_time_df.head()) # Get Interest by Region data interest_by_region_df = pytrends.interest_by_region(resolution='COUNTRY', inc_low_vol=True, inc_geo_code=True) print("\nInterest By Region (first 5 rows):") print(interest_by_region_df.head())
Debug
Known issues
breakingPytrends is an unofficial API and is prone to frequent breaking changes when Google updates its backend or internal API. This can lead to unexpected errors (e.g., 404, 500) or changes in expected behavior without prior notice.
fix
Always check for the latest `pytrends` version and consult the GitHub repository for recent fixes or workarounds. Installing directly from GitHub might be necessary for the latest patches.
affects: All versions
gotchaFrequent HTTP 429 (Too Many Requests) errors are common due to Google's rate limiting. This can occur even with seemingly low request volumes, especially from shared IP addresses (e.g., school networks).
fix
Introduce delays between requests (`time.sleep()`), reduce the number of requests, use proxies, or configure `retries` and `backoff_factor` when initializing `TrendReq`. Consider batching requests.
affects: All versions
gotchaGoogle Trends data is relative and scaled from 0-100. This means that if you pull data for a keyword in two separate requests, the absolute popularity between them cannot be directly compared. Comparisons are only valid when multiple keywords are requested within the *same* `build_payload` call.
fix
Always include all keywords you wish to compare within a single `kw_list` parameter when calling `build_payload()`.
affects: All versions
gotchaIncorrect timezone handling is a common pitfall. By default, Pytrends data is based on UTC. The `tz` parameter in `TrendReq` expects the timezone offset in minutes, but Google's internal handling often means positive values for 'west' of UTC (e.g., '360' for UTC-6, not '-360').
fix
Carefully determine the correct `tz` value for your target region. For example, US Central Standard Time (UTC-6) is `tz=360`. Refer to `pytrends` documentation or community resources for a list of common `hl` and `tz` pairs.
affects: All versions
gotchaHTTP 400 (Bad Request) errors can occur if the structure of the request payload is incorrect, unrelated to rate limits. This might involve invalid keyword combinations, unsupported timeframes, or malformed parameters.
fix
Review your `kw_list`, `timeframe`, `geo`, `cat`, and `gprop` parameters to ensure they are valid and correctly formatted according to Google Trends' expectations.
affects: All versions
Errors
Common errors & fixes
pytrends.exceptions.TooManyRequestsError: The request failed: Google returned a response with code 429
This error occurs when Google detects too many requests from the same IP address in a short period, triggering rate limiting.
fix
Implement request throttling by setting the 'retries' and 'backoff_factor' parameters in the TrendReq initialization to manage the frequency of requests. For example: 'pytrends = TrendReq(retries=3, backoff_factor=0.1)'.
pytrends.exceptions.ResponseError: The request failed: Google returned a response with code 500
A 500 error indicates an internal server error on Google's end, which can occur due to various reasons, including temporary issues with Google's servers.
fix
Retry the request after a short delay. If the error persists, check for any updates or issues with the pytrends library that might be causing the problem.
KeyError: "['query' 'value'] not in index"
This error occurs when the 'related_queries()' function is called for a keyword that doesn't have enough data, resulting in missing expected columns in the returned DataFrame.
fix
Before accessing the DataFrame, check if the 'top' and 'rising' keys exist in the dictionary returned by 'related_queries()'. If they don't, handle the absence gracefully to prevent the KeyError.
TypeError: TrendReq.trending_searches() missing 1 required positional argument: 'self'
This error occurs when 'trending_searches()' is called as a class method instead of an instance method.
fix
Create an instance of 'TrendReq' first, then call 'trending_searches()' on that instance. For example: 'pytrend = TrendReq(); trending_searches_df = pytrend.trending_searches(pn="united_states")'.
ModuleNotFoundError: No module named 'pytrends'
This error occurs when the 'pytrends' library is not installed in the Python environment.
fix
Install the 'pytrends' library using pip: 'pip install pytrends'.
Upgrade
Version history
4.9.2latest on PyPI · released Apr 13, 2023
Audit
Dependencies
requestsrequiredHandles HTTP requests to Google Trends.
lxmlrequiredUsed for parsing HTML responses.
pandasrequiredProvides DataFrame structures for data manipulation and output.
Agent activity
36 hits · last 30 days
node
34
Resources
pytrends — pip install pytrends · libregistry