python爬取疫情數據


日期 開始時間 結束時間 中斷時間 凈時間 活動 備注
3.10 3:40 5:45  20  105  查資料 查詢Json與python
 3.10  6:10  7:00    50 安裝軟件  用於學習python
 3.11  10:15  11:20  10  55   編代碼  學習python
 3:11  2:40  5:30  50  120  寫代碼  
 3.11  7:00  9:00  20  100  改代碼  

下面是爬取疫情數據代碼

import pymysql
import re
import json
from pip._vendor import requests


def create():
    db = pymysql.connect("localhost", "root", "123", "payiqing",charset='utf8')  # 連接數據庫

    cursor = db.cursor()
    cursor.execute("DROP TABLE IF EXISTS info")

    sql = """CREATE TABLE info(
            Id INT PRIMARY KEY AUTO_INCREMENT,
            Date varCHAR(255),
            Province varchar(255),
            City varchar(255),
            Confirmed_num varchar(255),
            Yisi_num varchar(255),
            Cured_num varchar(255),
            Dead_num varchar(255),
            Code varchar(255))"""

    cursor.execute(sql)

    db.close()


def insert(value):
    db = pymysql.connect("localhost", "root", "123", "payiqing",charset='utf8')

    cursor = db.cursor()
    sql = "INSERT INTO info(Date,Province,City,Confirmed_num,Yisi_num,Cured_num,Dead_num,Code) VALUES ( %s,%s,%s,%s,%s,%s,%s,%s)"
    try:
        cursor.execute(sql, value)
        db.commit()
        print('插入數據成功')
    except:
        db.rollback()
        print("插入數據失敗")
    db.close()


create()  # 創建表

url='https://raw.githubusercontent.com/BlankerL/DXY-2019-nCoV-Data/master/json/DXYArea.json'
response = requests.get(url)
# 將響應信息進行json格式化
versionInfo = response.text
# print(versionInfo)#打印爬取到的數據
# print("------------------------")#重要數據分割線↓

#一個從文件加載,一個從內存加載#json.load(filename)#json.loads(string)
jsonData = json.loads(versionInfo)

#用於存儲數據的集合
dataSource = []
provinceShortNameList = []
confirmedCountList = []
curedCount = []
deadCountList = []
#遍歷對應的數據存入集合中
for k in range(len(jsonData['results'])):
    if(jsonData['results'][k]['countryName'] == '中國'):
        provinceShortName = jsonData['results'][k]['provinceName']
        if("待明確地區" == provinceShortName):
            continue;

        for i in range(len(jsonData['results'][k]['cities'])):
            confirmnum=jsonData['results'][k]['cities'][i]['confirmedCount']
            yisi_num=jsonData['results'][k]['cities'][i]['suspectedCount']
            cured_num=jsonData['results'][k]['cities'][i]['curedCount']
            dead_num=jsonData['results'][k]['cities'][i]['deadCount']
            code=jsonData['results'][k]['cities'][i]['locationId']
            cityname=jsonData['results'][k]['cities'][i]['cityName']
            date='2020-3-10'
            insert((date,provinceShortName,cityname,confirmnum,yisi_num,cured_num,dead_num,code))

爬取出的數據導入數據庫表中:

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM