为什么我不能通过 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 个关键字时效果很好,但随着我添加更多关键字,它会中断。

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

谢谢

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)