The request failed: Google returned a response with code 400 with Pytrends Python Library for Google Trends API

Question:

I have the following code:

from pytrends.request import TrendReq

keywords = ['example1', 'example2', 'example3']

mapping = {}

pytrends = TrendReq()

for keyword in keywords[:3]:

    print(keyword)
    pytrends.build_payload(keyword,timeframe='today 12-m')
    trend_data = pytrends.interest_over_time()
    series = trend_data[keyword[0]]
    print(series)
    plt.plot(series)
    plt.show()
    mapping[keyword] = series
    time.sleep(65)

For the first keyword in the keywords array, this will work. However, as soon as the for loop iterates to the next keyword, I get "pytrends.exceptions.ResponseError: The request failed: Google returned a response with code 400".

Initially, I thought this was because of rate limits but I set time.sleep() in the for loop to over 1 minute in between requests. Any help would be much appreciated.

Asked By: Tekame1

||

Answers:

Maybe this will help. You need to pass a list into build_paylod() per the documentation. I suspect you want to compare the results in one chart, but if not this should at least get you closer:

from pytrends.request import TrendReq
import matplotlib.pyplot as plt

keywords = ['example1', 'example2', 'example3']

pytrends = TrendReq()

pytrends.build_payload(keywords,timeframe='today 12-m')
trend_data = pytrends.interest_over_time()
series = trend_data[keywords]
plt.plot(series)
plt.show()

This will give you a graph like:

enter image description here

Answered By: Mark
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.