因此,我编写了这个小程序来更新 Steam 市场上特定商品的最低价格,它运行一个循环并获取 json 响应。
最初它工作正常,显示价格,但一段时间后它显示错误。
程序代码:
import json
import requests
def GetPrice () :
response = requests.get ('https://steamcommunity.com/market/priceoverview/?appid=264710¤cy=1&market_hash_name=Planet%204546B%20Postcard')
json_data = {}
json_data = json.loads (response.text)
return json_data ["lowest_price"]
while True :
print (GetPrice ())
Run Code Online (Sandbox Code Playgroud)
这是程序的输出:
$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]
Run Code Online (Sandbox Code Playgroud)
小智 5
当您尝试索引某个类型的对象None(即:该对象没有值)时,会发生此错误。
这里你的None对象是你的json_data变量,这意味着json.loads (response.text)返回None。
您可以通过添加 if 语句来检查该值是否不存在来避免此错误None:
if json_data is not None:
return json_data['lowest_price']
return None
Run Code Online (Sandbox Code Playgroud)
或者使用 try- except 语句:
try:
return json_data['lowest_price']
except Exception as e:
return None # or you can raise an exception if you want
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
5244 次 |
| 最近记录: |