【问题标题】:Python - 'NoneType' object is not subscriptable (A Small Program For Steam Item Price)Python - 'NoneType' 对象不可下标(Steam 物品价格的小程序)
【发布时间】:2020-06-21 16:08:53
【问题描述】:

所以,我做了这个小程序来更新 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]

【问题讨论】:

  • 你有什么理由一遍又一遍地检查同一个网址吗?

标签: python steam


【解决方案1】:

当您尝试索引 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

【讨论】:

    【解决方案2】:

    您遇到了这个问题,因为您向服务器发出的请求非常快。

    具体来说,服务器回复http错误码429

    考虑在发送连续请求之前等待几秒钟。

    【讨论】:

      【解决方案3】:

      检查您的变量是否包含正确的数据。如果json_data 什么都没有,那么您将无法检索该值。说,json_data 是None 你需要检查变量。

      方法 1

      try:
          return json_data["lowest_price"]
      except Exception as e:
          print(json_data)
          print(e)
          return None
      

      方法2

      你可以明确检查json_data变量值

      if json_data != None:
          if "lowest_price" in json_data:
              return json_data["lowest_price"]
      

      【讨论】:

        【解决方案4】:

        所以有时您会收到导致问题的空响应

        try:
            price = json_data ["lowest_price"]
        except Exception as e:
            pass
        

        【讨论】:

          猜你喜欢
          • 2021-12-14
          • 1970-01-01
          • 1970-01-01
          • 2021-02-14
          • 2016-03-30
          • 2019-08-12
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多