本文示例程序的功能主要是获取湖北省各个地市每日降雨量数据。
降雨量数据地址:http://113.57.190.228:8001/web/Report/CantonRainSta
代码比较简单,就不详细注释了。
import requests
import json
import pandas as pd
import datetime
from sqlalchemy import create_engine
#初始化数据表结构,定义列名
df = pd.DataFrame(columns=['citycode','cityname','stime','etime','sehour','rainfall_mm'])
#传参,起止日期
begin = datetime.date(2023,7,1)
end = datetime.date(2023,12,31)
#逐日循环爬取降雨量
d = begin
delta = datetime.timedelta(days=1)
while d <= end:
#当日
startDate=d.strftime("%Y-%m-%d")
#次日
d += delta
endDate=d.strftime("%Y-%m-%d")
print (startDate,endDate)
#获取页面json格式数据
jsondata = requests.get(url='http://113.57.190.228:8001/web/report/GetRainReportData/?sdate='+startDate
+' 08:00'+'&edate='+endDate+' 08:00')
#提取内容
hjson = json.loads(jsondata.text)
#提取需要的数据
rows = hjson['rows']
#结构化处理,保存
for i in rows:
l=[[i['ADDVCD'],i['ADDVNM'],i['SUMRAIN']],[i['ADDVCD1'],i['ADDVNM1'],i['SUMRAIN1']]]
t = pd.DataFrame(l,columns=['citycode','cityname','rainfall_mm'])
t['stime']=startDate
t['etime']=endDate
t['sehour']='8:00'
df=pd.concat([df,t],ignore_index=True)
#降雨量字段转换为数值格式
df['rainfall_mm'] = pd.to_numeric(df['rainfall_mm'])
#保存为表格
df.to_excel('D:\python代码\降雨量爬虫\湖北省各地区降雨量数据-增量.xlsx',index=False)
#存储至本地postgres数据库
engine1 =create_engine('postgresql+psycopg2://postgres:root@localhost:5432/postgres')
try:
df.to_sql('hb_qy_jyl_zl',engine1,schema='sjsj',index=False,if_exists='replace')
except Exception as e:
print(e)