爱写算法的u 2023-02-09 20:29 采纳率: 23.1%
浏览 32
已结题

python爬取疫情数据存到数据库失败

将爬取的数据导入数据库失败
源代码:

def get_wangyi_data():
    url = "https://c.m.163.com/ug/api/wuhan/app/data/list-total"
    headers= {
    'user-agent':'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/92.0.4515.131 Safari/537.36 SLBrowser/8.0.0.12022 SLBChan/25'}
    r = requests.get(url=url,headers=headers)
    d = json.loads(r.text)
    data = json.dumps(d['data'])
    data_all = data.encode("utf-8").decode("unicode-escape")
    data_all = json.loads(data_all) ##提取我们所需要的数据
    history = {} #历史数据
    for i in data_all["chinaDayList"]:
        ds = i["date"]
        #ds=json.loads(ds)
        tup = time.strptime(ds,"%Y-%m-%d")
        ds = time.strftime("%Y-%m-%d",tup)#改变时间格式,不然插入数据库会出错,数据库是datetime类型
        confirm = i["total"]["confirm"]
        suspect = i["total"]["suspect"]
        heal = i["total"]["heal"]
        dead = i["total"]["dead"]
        history[ds] = {"confirm":confirm,"suspect":suspect,"heal":heal,"dead":dead}
        
    for i in data_all["chinaDayList"]:
        ds = i["date"]
        #ds=json.loads(ds)
        tup = time.strptime(ds,"%Y-%m-%d")
        ds = time.strftime("%Y-%m-%d",tup)#改变时间格式,不然插入数据库会出错,数据库是datetime类型
        confirm = i["today"]["confirm"]
        suspect = i["today"]["suspect"]
        heal = i["today"]["heal"]
        dead = i["today"]["dead"]
        history[ds].update ({"confirm_add":confirm,"suspect_add":suspect,"heal_add":heal,"dead_add":dead})
    details = [] #当日详细数据
    update_time = data_all["lastUpdateTime"]
    data_country = data_all["areaTree"] #25个国家
    data_province = data_country[2]["children"] #中国各省
    for pro_infos in data_province:
        province = pro_infos["name"] #省名
        for city_infos in pro_infos["children"]:
            city = city_infos["name"]
            confirm = city_infos["total"]["confirm"]
            confirm_add = city_infos["today"]["confirm"]
            heal = city_infos["total"]["heal"]
            dead = city_infos["total"]["dead"]
            details.append([update_time,province,city,confirm,confirm_add,heal,dead])
    return history, details


def get_conn():
    """
    :return:连接,游标
    """
    #创建连接
    conn = pymysql.connect(host = "127.0.0.1",
                          user = "root",
                          password = "root",
                          db = "cov",
                          charset = "utf8")
    
    #创建游标
    cursor = conn.cursor() #执行完毕返回的结果集默认以元组显示
    return conn,cursor

def close_conn(conn,cursor):
    if cursor:
        cursor.close()
    if conn:
        conn.close()

def update_details():
    """
    更新details表
    """
    
    cursor = None
    conn = None
    try:
        li = get_wangyi_data()[1] #0是历史数据字典,1是最新详细数据列表
        conn,cursor = get_conn()
        sql = "insert into datails(update_time,province,city,confirm,confirm_add,heal,dead) values(%s,%s,%s,%s,%s,%s,%s)"
        sql_query = "select %s=(select update_time from details order by id desc limit 1)" #对比当前最大时间戳
        cursor.execute(sql_query,li[0][0])
        if not cursor.fetchone()[0]:
            print(f"{time.asctime()}开始更新最新数据")
            for item in li:
                cursor.execute(sql,item)
            conn.commit()  #提交事务 update delete insert操作
            print(f"{time.asctime()}更新最新数据完毕")
        else:
            print(f"{time.asctime()}已是最新数据!")
    except:
        traceback.print_exc()
    finally:
        close_conn(conn,cursor)

update_details()

出现如下错误

img

但我数据库已创建这个表了

img

  • 写回答

1条回答 默认 最新

  • pzzhao 2023-02-09 20:59
    关注

    你的sql表名写错了,你的表是details,sql里写的是datails

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

问题事件

  • 已结题 (查看结题原因) 2月13日
  • 已采纳回答 2月9日
  • 创建了问题 2月9日

悬赏问题

  • ¥20 关于#stm32#的问题:需要指导自动酸碱滴定仪的原理图程序代码及仿真
  • ¥20 设计一款异域新娘的视频相亲软件需要哪些技术支持
  • ¥15 stata安慰剂检验作图但是真实值不出现在图上
  • ¥15 c程序不知道为什么得不到结果
  • ¥40 复杂的限制性的商函数处理
  • ¥15 程序不包含适用于入口点的静态Main方法
  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因