Python - 多次尝试访问 API 时出错

Python - Error occuring when trying to access an API more than once

我在学校编程,很快就需要编写我的最终作品。下面的程序(用 python 的编程语言编写)作为我编写的程序只是为了练习访问 APIs。 我正在尝试访问 API 以获得基于游戏的景象。该程序的想法是每 30 秒检查一次此 API 以检查数据的变化,只要它是 运行,然后将此数据与 30 秒后获取的新数据进行比较。 这是我的程序:

import time

apiKey = '###'
rankDifferences = []
ppDifferences = []
const = True

username = '- Legacy'
url = "https://osu.ppy.sh/api/get_user?u={1}&k={0}".format(apiKey,username)        
import urllib.request, json 
with urllib.request.urlopen(url) as url:
    stats = json.loads(url.read().decode())
stats = stats[0]

basePP = stats['pp_raw']
print(basePP)
baseRank = stats['pp_rank']
print(baseRank)

while const == True:
    time.sleep(30)
    import urllib.request, json 
    with urllib.request.urlopen(url) as url:
        check = json.loads(url.read().decode())
    check = check[0]

    rankDifference = baseRank + check['pp_rank']
    ppDifference = basePP + check['pp_raw']
    baseRank = check['pp_raw']
    basePP = check['pp_raw']

    if rankDifference != 0:
        print(rankDifference)

    if ppDifference != 0:
        print(ppDifference)`

请注意,在我写 'apiKey = '###'' 的地方,我实际上使用的是真实有效的 API 密钥,但我已按照网站要求将其隐藏不要与他人分享您的 api 密钥。 这是 shell 在 运行 之后的状态:

5206.55

12045

Traceback (most recent call last):

File "C:/Users/ethan/Documents/osu API Accessor.py", line 23, in with urllib.request.urlopen(url) as url: File

"C:\Users\ethan\AppData\Local\Programs\Python\Python36\lib\urllib\request.py", >line 223, in urlopen return opener.open(url, data, timeout)

File

"C:\Users\ethan\AppData\Local\Programs\Python\Python36\lib\urllib\request.py", >line 518, in open protocol = req.type

AttributeError: 'HTTPResponse' object has no attribute 'type'

如你所见,它确实打印了'basePP'和'baseRank',证明我可以访问这个API。问题似乎是当我第二次尝试访问它时。老实说,我不太确定这个错误是什么意思。所以如果你不介意花时间解释 and/or 帮助修复这个错误,我们将不胜感激。

旁注:这是我第一次使用这个论坛,所以如果我做错了什么,我很抱歉!

问题似乎出在您执行以下操作时:

with urllib.request.urlopen(url) as url:
    stats = json.loads(url.read().decode())

您对 url 变量的使用正在改变它,因此当您稍后尝试使用它时它不起作用。

试试这样的东西:

with urllib.request.urlopen(url) as page:
    stats = json.loads(page.read().decode())

应该没问题。