首页 > 解决方案 > 为什么我不能通过 PyTrends 遍历多个搜索词/关键字?列表索引超出范围错误?

问题描述

我试图通过以下 PyTrends 函数代码使用六个关键字:

def my_funct(Keyword, Dates, Country, Col_name):
    
    KEYWORDS=[Keyword] 
    KEYWORDS_CODES=[pytrend.suggestions(keyword=i)[0] for i in KEYWORDS] 
    df_CODES= pd.DataFrame(KEYWORDS_CODES)
    
    EXACT_KEYWORDS=df_CODES['mid'].to_list()
    
    DATE_INTERVAL= Dates
    COUNTRY=[Country] #Use this link for iso country code
    CATEGORY=0 # Use this link to select categories
    SEARCH_TYPE='' #default is 'web searches',others include 'images','news','youtube','froogle' (google shopping)


    Individual_EXACT_KEYWORD = list(zip(*[iter(EXACT_KEYWORDS)]*1))
    Individual_EXACT_KEYWORD = [list(x) for x in Individual_EXACT_KEYWORD]
    dicti = {}
    i = 1

    for Country in COUNTRY:
        for keyword in Individual_EXACT_KEYWORD:
            try:
                pytrend.build_payload(kw_list=keyword, 
                                      timeframe = DATE_INTERVAL,
                                      geo = Country, 
                                      cat = CATEGORY,
                                      gprop = SEARCH_TYPE) 
                dicti[i] = pytrend.interest_over_time()
                i+=1
                time.sleep(9)
                print(dicti)
                
            except requests.exceptions.Timeout:
                    print("Timeout occured")
        
    df_trends = pd.concat(dicti, axis=1)


    df_trends.columns = df_trends.columns.droplevel(0) #drop outside header
    df_trends = df_trends.drop('isPartial', axis = 1) #drop "isPartial"
    df_trends.reset_index(level=0,inplace=True) #reset_index
    df_trends.columns=['date', Col_name] #change column names
  

    return df_trends

这是执行它的代码:

x1 = my_funct('Nike+Puma+Adidas+New Balance+Gucci+Prada', '2004-01-04 2009-01-04', 'DK', 'Fashion keywords')

当我执行该代码时,我收到此错误:

    KEYWORDS_CODES=[pytrend.suggestions(keyword=i)[0] for i in KEYWORDS]

IndexError: list index out of range

它适用于 1 个关键字,但随着我添加更多它会中断。

请,非常感谢任何和所有的帮助。

谢谢

标签: pythonlistloopsgoogle-trends

解决方案


推荐阅读