urllib not working with api request
即时通讯尝试编写此代码,我从openweathermap.org请求此信息thourgh api并尝试打印当前时间的温度和位置。
大多数代码都是我在互联网上找到的一些技巧。
现在我收到了这个错误并且卡住了。 谁能帮助我再次走上正确的道路?
继承我的代码:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 | import urllib.request, urllib.parse, urllib.error import json while True: zipcode = input('Enter zipcode: ') if len(zipcode) < 1: break url = 'http://api.openweathermap.org/data/2.5/weather? zip='+zipcode+',nl&appid=db071ece9a338a36e9d7a660ec4f0e37?' print('Retrieving', url) uh = urllib.request.urlopen(url) data = uh.read().decode() print('Retrieved', len(data), 'characters') try: js = json.loads(data) except: js = None temp = js["main"]["temp"] loc = js["name"] print("temperatuur:", temp) print("locatie:", loc) |
所以网址是这样的:http://api.openweathermap.org/data/2.5/weather?zip = 3032,nl&appid = db071ece9a338a36e9d7a660ec4f0e37
我得到的错误是:
Enter zipcode: 3343
Retrieving http://api.openweathermap.org/data/2.5/weather?zip=3343,nl&appid=db071ece9a338a36e9d7a660ec4f0e37?
Traceback (most recent call last):
File"weatherapi2.py", line 12, in
uh = urllib.request.urlopen(url)
File"C:\Users\ErfanNariman\AppData\Local\Programs\Python\Python36\lib\urllib
equest.py", line 223, in urlopen
return opener.open(url, data, timeout)
File"C:\Users\ErfanNariman\AppData\Local\Programs\Python\Python36\lib\urllib
equest.py", line 532, in open
response = meth(req, response)
File"C:\Users\ErfanNariman\AppData\Local\Programs\Python\Python36\lib\urllib
equest.py", line 642, in http_response
'http', request, response, code, msg, hdrs)
File"C:\Users\ErfanNariman\AppData\Local\Programs\Python\Python36\lib\urllib
equest.py", line 570, in error
return self._call_chain(*args)
File"C:\Users\ErfanNariman\AppData\Local\Programs\Python\Python36\lib\urllib
equest.py", line 504, in _call_chain
result = func(*args)
File"C:\Users\ErfanNariman\AppData\Local\Programs\Python\Python36\lib\urllib
equest.py", line 650, in http_error_default
raise HTTPError(req.full_url, code, msg, hdrs, fp)
urllib.error.HTTPError: HTTP Error 401: Unauthorized
经过一些故障排除后我发现了你的问 你有一个额外的'?' 在你的python的url的末尾。
删除它,您的请求工作正常。 尝试使用此代码并使用 -
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 | import urllib.request, urllib.parse, urllib.error import json while True: zipcode = input('Enter zipcode: ') if len(zipcode) < 1: break url = 'http://api.openweathermap.org/data/2.5/weather?zip='+zipcode+',nl&appid=db071ece9a338a36e9d7a660ec4f0e37' print('Retrieving', url) uh = urllib.request.urlopen(url) data = uh.read().decode() print('Retrieved', len(data), 'characters') try: js = json.loads(data) except: js = None temp = js["main"]["temp"] loc = js["name"] print("temperatuur:", temp) print("locatie:", loc) |