首页 > 解决方案 > Python KeyError:'destinationAccount'

问题描述

我从正在抓取数据的网站上编写了具有以下结构的代码:

destinationAccount:
   ownerBuilding: ( collapse to destinationAccount)
     label: ( collapse to ownerBuilding )
     _id: ( collapse to ownerBuilding )
vban: ( collapse to destinationAccount)
_id: ( collapse to destinationAccount)

当我尝试用这个阅读这个密钥时

vban = str(transaction["destinationAccount"]["vban"])

它给了我KeyError: 'destinationAccount'

任何人都知道为什么会出现这种情况?当我运行我的代码时,它会将我需要的所有内容复制到 MySQL 数据库中,但正如我已经说过的,KeyError 弹出窗口和间隔不起作用

sched = BlockingScheduler()
sched.add_job(start, 'interval', seconds=5)
sched.start()

因为它在出现错误后停止运行。当我注释掉这个时,vban = str(transaction["destinationAccount"]["vban"])不会出现错误。我现在检查了 10 多次,我在顶部显示的结构在网站上。任何解决方案都会很棒。

def getData():
    databaseConn = dbConnect()
    cursor = databaseConn.cursor()

    for x in range(3):
        x = x * 25
        transactions = json.loads(makeRequest("URL.bla/transactions?offset=" + str(x), authToken, True).text)
        for transaction in transactions:
            person = ""
            try:
                person = transaction["destinationAccount"]["ownerCharacter"]["name"]
            except:
                try:
                    person = transaction["destinationAccount"]["ownerFactory"]["label"]
                except:
                    try:
                        person = transaction["destinationAccount"]["ownerBuilding"]["label"]
                    except:
                        person = str("unbekannt")

            reference = ""
            try:
                reference = str(translateTable[transaction["reference"]])
            except:
                reference = str(transaction["reference"])

            vban = str(transaction["destinationAccount"]["vban"])
            amount = str(transaction["amount"])
            taxAmount =str(transaction["taxAmount"])
            gesamt = (float(amount) + float(taxAmount))

            created = parse(str(transaction["created"]))
            date = str(created.date())
            time = str(created.time()).split(".")[0]

            sql = "INSERT INTO finanzen (transaktion, date, time, sendto, vban, amount, tax, gesamt, text) VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s)"
            val = (str(transaction["uuid"]), date, time, str(person), vban, amount, taxAmount, gesamt, reference)
            try:
               cursor.execute(sql, val)
               databaseConn.commit()
            except:
                print("Fehler Datenbank")
    dbClose(databaseConn,cursor)

打印结果:

{'_id': 'CENSORED', 
'uuid': 'CENSORED', 
'amount': 11.8421, 
'taxAmount': 3.1479, 
'type': 'digital', 
'created': 'Date', 
'reference': 'CENSORED', 
'sourceAccount': {'_id': 'CENSORED', 
'ownerCharacter': {'_id': 'CENSORED', 
'name': 'NAME'}, 
'vban': 'NUMBER'}, 
'destinationAccount': {'_id': 'CENSORED', 
'vban': 'NUMBER', 
'ownerBuilding': {'_id': 'CENSORED', 
'label': 'Eclipse Towers'}}}

标签: pythonweb-scrapingpython-requests

解决方案


很难看不到完整的清单,但我怀疑有些项目缺少关键。您是否尝试过检查现有的密钥。使用您的示例:

transaction = {
   "_id":"CENSORED",
   "uuid":"CENSORED",
   "amount":11.8421,
   "taxAmount":3.1479,
   "type":"digital",
   "created":"Date",
   "reference":"CENSORED",
   "sourceAccount":{
      "_id":"CENSORED",
      "ownerCharacter":{
         "_id":"CENSORED",
         "name":"NAME"
      },
      "vban":"NUMBER"
   },
   "destinationAccount":{
      "_id":"CENSORED",

      "ownerBuilding":{
         "_id":"CENSORED",
         "label":"Eclipse Towers"
      }
   }
}

if 'vban' in transaction['destinationAccount']:
    vban = str(transaction["destinationAccount"]["vban"])
else:
    vban = "none"

推荐阅读