基于Python的河南省天气数据分析与空气质量预测研究【含数据抓取与数据库自动存储】
import requests
import pymysql
import pandas as pd
# 天气API接口
api_url = "http://api.yhcloud.com/weather_v2/now?location=郑州"
# 连接数据库
connection = pymysql.connect(host='localhost', user='your_username', password='your_password', db='your_database', charset='utf8mb4')
try:
# 抓取天气数据
response = requests.get(api_url)
data = response.json()
# 解析数据
city = data['city']
update_time = data['update_time']
weather = data['data']['weather']
temperature = data['data']['temperature']
humidity = data['data']['humidity']
wind = data['data']['wind']
# 将数据存入数据库
with connection.cursor() as cursor:
sql = "INSERT INTO weather_data (city, update_time, weather, temperature, humidity, wind) VALUES (%s, %s, %s, %s, %s, %s)"
cursor.execute(sql, (city, update_time, weather, temperature, humidity, wind))
connection.commit()
print("数据已成功存入数据库")
except pymysql.MySQLError as e:
print(f"Error: {e}")
finally:
connection.close()
这段代码展示了如何使用Python从一个假设的API获取天气数据,并将其存储到MySQL数据库中。代码中包含了异常处理,以确保在发生错误时能够优雅地处理。需要注意的是,在实际应用中,你需要替换掉数据库连接信息,并确保你的数据库结构与代码中的SQL语句相匹配。
评论已关闭