如何解决为什么即时获取类型为'NoneType'的参数是不可迭代的
每当我运行此代码时,我都会收到TypeError
import urllib
import json
serviceurl = 'http://python-data.dr-chuck.net/geojson?'
address = input('Enter location: ')
url = serviceurl + urllib.parse.urlencode({'sensor':'false','address': address})
print ('Retrieving',url)
uh = urllib.request.urlopen(url)
data = uh.read()
print ('Retrieved',len(data),'characters')
try:
js = json.loads(str(data))
except:
js = None
if 'status' not in js or js['status'] != 'OK':
print ('==== Failure To Retrieve ====')
print (data )
placeid = js["results"][0]["place_id"]
print ('Place ID ',placeid)
if 'status' not in js or js['status'] != 'OK':
print ('==== Failure To Retrieve ====')
print (data )
placeid = js["results"][0]["place_id"]
print ('Place ID ',placeid)
Enter location: Moscow Engineering-Physics Institute
Retrieving http://python-data.dr-chuck.net/geojson?sensor=false&address=Moscow+Engineering-Physics+Institute
Retrieved 3480 characters
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-32-4cd76de63011> in <module>
13 except: js = None
14
---> 15 if 'status' not in js or js['status'] != 'OK':
16 print ('==== Failure To Retrieve ====')
17 print (data )
TypeError: argument of type 'NoneType' is not iterable
解决方法
您的错误表示js为None或undefined。 Python说js为None,因此不可迭代。 由于使用python,当您执行“某物变种”时,它希望某物可以像列表或集合那样被迭代。
您可以通过简单的if来测试某项是否为None。 这有点令人困惑,但是在python 0中,if语句将None和False评估为false。
your code...
if js:
# do your code
else:
# js is not defined you may want to do something or not.
在try-except块中,您将js专门设置为None,以防失败。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。