javascript - 我不明白为什么我的处理格式参数失败;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()
解决方案
我会尝试从 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']) ...)
推荐阅读
- g++ - 在较旧的 g++ 环境中使用 c++17 预编译头文件
- javascript - 如何编码像“\u00c3\u00a7”这样的unicode序列?
- protocol-buffers - 在没有它们的情况下解析协议缓冲区数据
- asp.net-mvc - 在请求正文中将数据发布到另一个应用程序
- python - 有没有办法关联 n 个数组?
- javascript - 有没有办法将深度嵌套对象的所有值类型都定义为字符串类型?
- drupal - 如何从分类术语页面隐藏节点内容?
- python - 有没有办法在字典中获取最大的键值,并打印它的项目
- go - Golang big.Float 的精度问题
- mysql - 从每组中选择 N 个值