urllib 不适用于 api 请求

urllib not working with api request

我正在尝试编写此代码,我通过 api 从 openweathermap.org 请求此信息,并尝试打印当前时间的温度和位置。

大部分代码都是我在互联网上找到的技巧的混合体。

现在我收到这个错误并且卡住了。任何人都可以帮助我再次走上正确的道路吗?

这是我的代码:

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)

所以 url 是这样的: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\request.py", line 223, in urlopen return opener.open(url, data, timeout) File "C:\Users\ErfanNariman\AppData\Local\Programs\Python\Python36\lib\urllib\request.py", line 532, in open response = meth(req, response) File "C:\Users\ErfanNariman\AppData\Local\Programs\Python\Python36\lib\urllib\request.py", line 642, in http_response 'http', request, response, code, msg, hdrs) File "C:\Users\ErfanNariman\AppData\Local\Programs\Python\Python36\lib\urllib\request.py", line 570, in error return self._call_chain(*args) File "C:\Users\ErfanNariman\AppData\Local\Programs\Python\Python36\lib\urllib\request.py", line 504, in _call_chain result = func(*args) File "C:\Users\ErfanNariman\AppData\Local\Programs\Python\Python36\lib\urllib\request.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 的末尾。

删除它,您的请求就可以正常工作。用这段代码试了一下,成功了——

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)