pythongoogle-trends

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


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.


Solution

  • 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