import requests
from bs4 import BeautifulSoup
import json
import time
from pymysql import * def mes():
url = 'https://ncov.dxy.cn/ncovh5/view/pneumonia?from=timeline&isappinstalled=0' #请求地址
headers = {'user-agent':'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/76.0.3809.87 Safari/537.36 SLBrowser/6.0.1.6181'}#创建头部信息
resp = requests.get(url,headers = headers) #发送网络请求
content=resp.content.decode('utf-8')
soup = BeautifulSoup(content, 'html.parser')
listA = soup.find_all(name='script',attrs={"id":"getAreaStat"})
account =str(listA)
mes = account.replace('[<script id="getAreaStat">try { window.getAreaStat = ', '')
mes=mes.replace('}catch(e){}</script>]','')
#mes=account[52:-21]
messages_json = json.loads(mes)
print(messages_json)
times=time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time()))
print(times)
provinceList=[]
cityList=[]
lenth=total()
con=len(messages_json)+lenth#算出数据库已有的条数+今天省份的条数,才是城市的开始id
for item in messages_json:
lenth+=1
provinceName=item['provinceName']
confirmedCount=item['confirmedCount']
suspectedCount=item['suspectedCount']
curedCount=item['curedCount']
deadCount=item['deadCount']
cities=item['cities']
provinceList.append((lenth,times,provinceName,None,confirmedCount,suspectedCount,curedCount,deadCount))
for i in cities:
con+=1
provinceName = item['provinceName']
cityName=i['cityName']
confirmedCount = i['confirmedCount']
suspectedCount = item['suspectedCount']
curedCount = i['curedCount']
deadCount = i['deadCount']
cityList.append((con,times,provinceName,cityName,confirmedCount,suspectedCount,curedCount,deadCount))
insert(provinceList,cityList) def insert(provinceList, cityList):
provinceTuple=tuple(provinceList)
cityTuple=tuple(cityList)
cursor = db.cursor()
sql = "insert into info_new values (%s,%s,%s,%s,%s,%s,%s,%s) "
try:
cursor.executemany(sql,provinceTuple)
print("插入成功")
db.commit()
except Exception as e:
print(e)
db.rollback()
try:
cursor.executemany(sql,cityTuple)
print("插入成功")
db.commit()
except Exception as e:
print(e)
db.rollback()
cursor.close()
def total():
sql= "select * from info_new"
cursor = db.cursor()
try:
cursor.execute(sql)
results = cursor.fetchall()
lenth = len(results)
db.commit()
return lenth
except:
print('执行失败,进入回调1')
db.rollback() # 连接数据库的方法
def connectDB():
try:
db = connect(host='localhost', port=3306, user='root', password='password', db='virus',charset='utf8')
print("数据库连接成功")
return db
except Exception as e:
print(e)
return NULL
if __name__ == '__main__':
db=connectDB()
mes()

数据库结构:

python爬取疫情数据存入MySQL数据库的更多相关文章

  1. python爬取疫情数据详解

    首先逐步分析每行代码的意思: 这是要引入的东西: from os import path import requests from bs4 import BeautifulSoup import js ...

  2. 利用Python爬取疫情数据并使用可视化工具展示

    import requests, json from pyecharts.charts import Map, Page, Pie, Bar from pyecharts import options ...

  3. Python爬取豆瓣音乐存储MongoDB数据库(Python爬虫实战1)

    1.  爬虫设计的技术 1)数据获取,通过http获取网站的数据,如urllib,urllib2,requests等模块: 2)数据提取,将web站点所获取的数据进行处理,获取所需要的数据,常使用的技 ...

  4. 如何使用Python爬取基金数据,并可视化显示

    本文的文字及图片来源于网络,仅供学习.交流使用,不具有任何商业用途,版权归原作者所有,如有问题请及时联系我们以作处理 以下文章来源于Will的大食堂,作者打饭大叔 前言 美国疫情越来越严峻,大选也进入 ...

  5. 毕设之Python爬取天气数据及可视化分析

    写在前面的一些P话:(https://jq.qq.com/?_wv=1027&k=RFkfeU8j) 天气预报我们每天都会关注,我们可以根据未来的天气增减衣物.安排出行,每天的气温.风速风向. ...

  6. 使用selenium再次爬取疫情数据(链接数据库)

    爬取网页地址: 丁香医生 数据库连接代码: def db_connect(): try: db=pymysql.connect('localhost','root','zzm666','payiqin ...

  7. 用Python爬取股票数据,绘制K线和均线并用机器学习预测股价(来自我出的书)

    最近我出了一本书,<基于股票大数据分析的Python入门实战 视频教学版>,京东链接:https://item.jd.com/69241653952.html,在其中用股票范例讲述Pyth ...

  8. python爬取网站数据

    开学前接了一个任务,内容是从网上爬取特定属性的数据.正好之前学了python,练练手. 编码问题 因为涉及到中文,所以必然地涉及到了编码的问题,这一次借这个机会算是彻底搞清楚了. 问题要从文字的编码讲 ...

  9. Python爬取房产数据,在地图上展现!

    小伙伴,我又来了,这次我们写的是用python爬虫爬取乌鲁木齐的房产数据并展示在地图上,地图工具我用的是 BDP个人版-免费在线数据分析软件,数据可视化软件 ,这个可以导入csv或者excel数据. ...

随机推荐

  1. mapboxgl 互联网地图纠偏插件(三)

    先说结论,结论当然是:大功告成,喜大普奔.看效果图: 好了,接下来说一下过程 先回顾一下这个系列的第一篇和第二篇 第一篇是直接改的 mapboxgl 源码,在源码里面对瓦片的位置进行纠偏,遇到的问题是 ...

  2. sqli-labs 16-20

    less 16: 和less 15基本一致,只是对参数进行了 ") 的包裹,注意闭合语句使用延时注入即可. 下面给一个payload示例: uname=admin")and if( ...

  3. FirstGradle

    一.导入依赖 二.build.gradle 整合SpringBoot plugins { id 'java' } group 'com.qiang' version '1.0.0-SNAPSHOT' ...

  4. idea的properties文件乱码问题解决

    设置编码格式: File============>Settings,打开设置后,设置成下面的即可解决:

  5. .NET Core垃圾收集

    在本章中,我们将介绍垃圾收集的概念,垃圾收集是.NET托管代码平台最重要的特性之一. 垃圾收集器(GC)管理内存的分配和释放. 垃圾收集器用作自动内存管理器. 我们不需要知道如何分配和释放内存或管理使 ...

  6. Monitor 类

    命名空间:System.Threading 程序集: mscorlib.dll, System.Threading.dll 尝试获取指定对象的排他锁. 用于 Monitor 锁定对象 (即引用类型) ...

  7. .Net 5 新特性之--支持字典在迭代中进行修改

    我们都知道以前字典迭代中是不支持动态修改的[否则会报错::"Collection was modified; enumeration operation may not execute.&q ...

  8. 【java web】过滤器、拦截器、监听器的区别

    一.对比: 1.1 过滤器和拦截器的区别: ①拦截器是基于java的反射机制的,而过滤器是基于函数回调. ②拦截器不依赖与servlet容器,过滤器依赖与servlet容器. ③拦截器只能对actio ...

  9. ProjectEuler 006题

    题目: The sum of the squares of the first ten natural numbers is, 12 + 22 + ... + 102 = 385 The square ...

  10. 哈希表(HashMap)分析及实现(JAVA)

    转自:http://www.java3z.com/cwbwebhome/article/article8/83560.html?id=4649 探讨Hash表中的一些原理/概念,及根据这些原理/概念, ...