大二下学期第一次结对作业(第二阶段)

由于第二阶段是全球疫情可视化,需要全球的疫情信息,所以需要爬取全球疫情信息。

由于第一阶段全国疫情可视化是爬取的腾讯疫情信息,为了表结构的相对统一,这次仍

然爬取腾讯的疫情信息:

首先是爬取的地址utl=https://api.inews.qq.com/newsqa/v1/automation/foreign/country/ranklist

观察一下数据的结构:

获取数据信息:

    r_world = requests.get(url_world, headers)
    res_world = json.loads(r_world.text)
    data_world = res_world['data']

整理有用的信息:

    world=[]
    for i in data_world:
        ds = i['y']+"."+i['date']
        tup = time.strptime(ds, "%Y.%m.%d")
        ds = time.strftime("%Y-%m-%d", tup)
        world.append([ds,i['name'],i['continent'],i['confirmAdd'],i['confirm'],i['suspect'],i['dead'],i['heal'],i['nowConfirm']])

这时可以查看整理后的数据:

 

 在插入数据库即可

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

 

posted @ 2021-03-23 11:20  风吹过半夏  阅读(44)  评论(0)    收藏  举报