在生成GET请求JSON文件时,Python | keyror'totalResults'

2024-09-26 22:52:09 发布

您现在位置:Python中文网/ 问答频道 /正文

我使用Foursquare explore API和categoryId查询特定半径内每个类别的场馆数量。响应包含指定坐标、半径和类别的totalResults值

def get_venues_count(latitudes, longitudes, radius, categoryId):
    explore_url = 'https://api.foursquare.com/v2/venues/explore?client_id={}&client_secret={}&v={}&ll={},{}&radius={}&categoryId={}'.format(
                CLIENT_ID, 
                CLIENT_SECRET, 
                VERSION,
                lat,
                lng,
                radius,
                categoryId)

    #make the GET request
    return requests.get(explore_url).json()['response']['totalResults']

#Create new dataframe to store venues data
stations_venues_df = df.copy()
for c in categories_list:
    stations_venues_df[c[0]] = 0

#Request number of venues, store result as CSV
for i, row in stations_venues_df.iterrows():
    print(i)
    for c in categories_list:        
        stations_venues_df.loc[i, c[0]] = get_venues_count(stations_venues_df.Latitude.iloc[i],
                                                           stations_venues_df.Longitude.iloc[i],
                                                           radius=500,
                                                           categoryId=c[1])
    stations_venues_df.to_csv('stations_venues.csv')

我运行了很多次,但每次它只生成了几行,然后停止并显示此错误:

KeyError                                  Traceback (most recent call last)
<ipython-input-22-551e888d2436> in <module>
      6                                                            stations_venues_df.Longitude.iloc[i],
      7                                                            radius=500,
----> 8                                                            categoryId=c[1])
      9     stations_venues_df.to_csv('stations_venues.csv')

<ipython-input-20-c9e33ae6e146> in get_venues_count(latitudes, longitudes, radius, categoryId)
     10 
     11     # make the GET request
---> 12     return requests.get(explore_url).json()['response']['totalResults']

KeyError: 'totalResults'

Tags: csvtoinurldfforgetcount
1条回答
网友
1楼 · 发布于 2024-09-26 22:52:09

我猜返回的响应是无效的(或者具有您期望的不同json格式)

我建议添加一个检查“totalResults”是否在json()[“Response”]字典中。 如果没有,那么您将知道返回的原因和类型

相关问题 更多 >

    热门问题