【问题标题】:Python: Google API if loopPython:Google API if 循环
【发布时间】:2017-11-06 01:22:45
【问题描述】:

我正在检查 Google API 响应:

url = 'https://maps.googleapis.com/maps/api/place/textsearch/json?'                 
params = {'location': '-38.30000000,176.15000000',                                   
          'radius': '5000',                                             
          'type': 'movie_theater',
          'key': 'MY_KEY'}                                                      
response = requests.get(url = url, params=params)       
# if response.status_code == 200:                                                   
response_data = response.json()                                                     

if 'results' in response_data:
    print ('There are results')
elif response_data['status'] == 'ZERO_RESULTS':
    print ('nothing')

如果您使用 Postman 搜索该特定位置:

https://maps.googleapis.com/maps/api/place/textsearch/json?location=-38.30000000,176.15000000&radius=5000&type=movie_theater&key=MY_KEY

没有电影院和 Google API 报告:

{
  "html_attributions": [],
  "results": [],
  "status": "ZERO_RESULTS"
}

不幸的是,我的ifelif 似乎无法正常工作,因为它无法打印nothing。 我哪里错了?

【问题讨论】:

    标签: python json google-maps postman


    【解决方案1】:

    但“结果”在响应数据中。它只包含一个空列表。

    解决此问题的一种方法可能是交换条件的顺序。

    【讨论】:

      【解决方案2】:

      您正在检查response_data中是否存在result key,它存在,所以“有结果”是正确的。您可以检查 reponse_data['results'] 的 len,如果长度为 0,则不打印任何内容。

      【讨论】:

        【解决方案3】:

        您应该将代码修改为:

        if len(response_data['results']) in response_data:
            print ('There are results')
        
        elif response_data['status'] == 'ZERO_RESULTS':
            print ('nothing')
        

        只需改变条件的顺序:

        if response_data['status'] == 'ZERO_RESULTS':
            print ('nothing')
        
        elif 'results' in response_data:
            print ('There are results')
        

        【讨论】:

          【解决方案4】:

          其他答案都是对的,你需要检查'results'数组的长度。

          Python 会伪造空数组,而 dict 中的 .get() 将默认为 None,因此您也可以简单地这样做:

          if response_data.get('results'):
              print ('yay! we have results')
          

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 1970-01-01
            • 2018-10-22
            • 2016-02-10
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2012-08-04
            相关资源
            最近更新 更多