gpt4 book ai didi

Python - 'NoneType' 对象不可下标(Steam 商品价格小程序)

转载 作者:行者123 更新时间:2023-12-05 00:56:18 28 4
gpt4 key购买 nike

所以,我做了这个小程序来更新 Steam 市场上特定商品的最低价格,它运行一个循环并获得 json 响应。

一开始可以正常工作,显示价格,但过了一会儿就显示错误。

程序代码:

import json
import requests

def GetPrice () :

response = requests.get ('https://steamcommunity.com/market/priceoverview/?appid=264710&currency=1&market_hash_name=Planet%204546B%20Postcard')

json_data = {}
json_data = json.loads (response.text)

return json_data ["lowest_price"]

while True :

print (GetPrice ())

这是程序的输出:

$1.03
$1.03
$1.03
$1.03
$1.03
$1.03
$1.03
$1.03
$1.03
$1.03
$1.03
$1.03
$1.03
$1.03
$1.03
$1.03
$1.03
$1.03
$1.03
$1.03
$1.03
$1.03
Traceback (most recent call last):
File "C:\Users\Admin\Desktop\item_price.py", line 16, in <module>
print (GetPrice ())
File "C:\Users\Admin\Desktop\item_price.py", line 12, in GetPrice
return json_data ["lowest_price"]
TypeError: 'NoneType' object is not subscriptable
[Finished in 20.2s]

最佳答案

当您尝试索引类型为 None 的对象时会发生此错误(即:该对象没有值)。

这里你的 None 对象是你的 json_data 变量,这意味着 json.loads (response.text) 返回 None

您可以通过添加一个 if 语句来检查值是否不是 None 来避免此错误:

if json_data is not None:
return json_data['lowest_price']
return None

或者使用 try-except 语句:

try:
return json_data['lowest_price']
except Exception as e:
return None # or you can raise an exception if you want

关于Python - 'NoneType' 对象不可下标(Steam 商品价格小程序),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62501163/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com