首页 > 解决方案 > 我不明白为什么我的处理格式参数失败;Python'列表'再次

问题描述

我一整天都在使用相同的代码,它一直在工作,由于某种原因,现在我正在做的新页面让我知道它是小东西,但我不断收到错误处理格式参数失败;Python'列表'

我试图像以前一样将起源添加为一个词,这次它没有用,我完全不知所措

import urllib.parse
import requests
import mysql.connector
import pandas as pd


mydb = mysql.connector.connect(
  host="localhost",
  user="root",
  passwd="******",
  database="flightdata"
)

mycursor = mydb.cursor()

url = 'https://www.launcestonairport.com.au/airportfeed.json'
response_data = requests.get(url).json()
# empty list for holding all the data
data = []
for element in response_data['departures']:
    origin = ["Launceston"]
    flight_id = element['AirLineID']
    airline = element['AirLineName']
    destination = element['Route1']
    flightNumbers = element['FlightID']
    scheduledTime = element['Scheduled']
    estimatedTime = element['Estimated']
    scheduledDate = element['DateFormatted']
    latestTime = element['Estimated']
    status = element['Status']
    gate = element['Gate']
    print(origin, flight_id, flightNumbers, airline, destination, 
          scheduledTime, scheduledDate, latestTime, gate, status)

    sql = "INSERT INTO flightinfo (origin, id, airline, destinations, flightNumbers, scheduledTime, estimatedTime, scheduledDate, latestTime, gate, status) VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s)"

    val = (origin, flight_id, airline, " ".join(destination), ", ".join(flightNumbers), scheduledTime, estimatedTime,
            scheduledDate, latestTime, status, gate)
    data.append(val)

# doing a batch insert
mycursor.executemany(sql, data)
mydb.commit()

标签: javascriptpythonjson

解决方案


我会尝试从 origin 变量中删除 [],因为你说它是一个列表(只保留 origin = "Launceston"),它应该只是字符串。该查询尝试将列表(或数组)转换为字符串值,但它拒绝了(恕我直言)。

编辑:至少“状态”,可能“门”也是一个列表(尝试使用 print(type(status)) 进行调试)。您需要显式转换为字符串(str(status),str(gate)..或使用join(),因为您正在使用其他变量)。

EDIT2:您可以创建清理函数,您可以根据需要处理空字符串、空列表。对于您的情况,这可能就足够了:

def sanitize(var):
    if not var: # [] is None
        return None

    return str(var) 

然后在对变量的每个分配中使用此函数(例如 status = sanitize(element['status']) ...)


推荐阅读