基于python+flask+mysql的川渝地区天气数据分析系统

server/2025/3/6 16:29:21/

系统首页

 


天气数据分析 


 历史天气数据查询

 


python爬虫代码展示

import requests
import re
import time as delay
from bs4 import BeautifulSoup
import pandas as pd
import pymysql
import json# 定义一个函数,用于获取网页的源代码
def get_page(url, headers):html = requests.get(url, headers=headers)if html.status_code == 200:html.encoding = html.apparent_encodingreturn html.textelse:print("Failed to fetch page:", url)  # 添加调试语句return None# 定义一个函数,用于解析网页中的数据,并返回一个数据框
def parse_page(html):# 创建空列表,用于存储数据date_box=[]max_temp=[]min_temp=[]weh=[]wind=[]# 使用 BeautifulSoup 解析网页bs=BeautifulSoup(html,'html.parser')# 找到包含数据的标签data=bs.find_all(class_='thrui')# 使用正则表达式提取数据date = re.compile('class="th200">(.*?)</div>')tem = re.compile('class="th140">(.*?)</div>')time = re.findall(date, str(data))for item in time:# 不提取星期数据date_box.append(item[:10])temp = re.findall(tem, str(data))for i in range(len(temp) // 4):max_temp.append(temp[i * 4 + 0])min_temp.append(temp[i * 4 + 1])weh.append(temp[i * 4 + 2])wind.append(temp[i * 4 + 3])# 将数据转换为数据框,不添加星期列datas=pd.DataFrame({'日期':date_box,'最高温度':max_temp,'最低温度':min_temp,'天气':weh,'风向':wind })return datas# 定义一个函数,用于将数据框中的数据保存到 mysql 数据表中
def save_to_mysql(datas, city, db, cursor):  # 添加城市参数for i in range(len(datas)):date = datas.iloc[i, 0]max_temp = float(re.findall(r'\d+', datas.iloc[i, 1])[0])min_temp = float(re.findall(r'\d+', datas.iloc[i, 2])[0])weh = datas.iloc[i, 3]wind = datas.iloc[i, 4]# 在 SQL 语句中包含城市信息sql = "INSERT INTO lishiweathers (城市, 日期, 最高温度, 最低温度, 天气, 风向) VALUES ('{}', '{}', {}, {}, '{}', '{}')".format(city, date, max_temp, min_temp, weh, wind)cursor.execute(sql)db.commit()print("成功将数据保存到 lishiweathers 表中")def crawl_weather(city, code, start, end, db, cursor):# 根据城市的编码和时间范围,生成网页的 urlurl = "http://lishi.tianqi.com/{}/{}{}.html".format(code, start, end)# 定义请求头,模拟浏览器访问headers = {  # 请求标头,通过模拟请求标头以此实现仿人类登录进入网站并获取信息'User-Agent': 'Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.132 Safari/537.36','Cookie': ******************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************}try:# 获取网页的源代码html = get_page(url, headers)# 解析网页中的数据,并返回一个数据框datas = parse_page(html)# 将数据框中的数据保存到 mysql 数据表中save_to_mysql(datas, city, db, cursor)  # 传递 cursor 参数# 打印提示信息,不打印星期数据,也不将其作为输出的格式print("成功爬取 {} 的 {}-{} 的历史天气数据".format(city, start, end))except Exception as e:print("爬取 {} 的 {}-{} 历史天气数据失败:{}".format(city, start, end, e))# 从本文件夹下的 city.json 文件中读取城市名称和编码
with open('city.json', 'r', encoding='utf-8') as f:city_dict = json.load(f) # 将json文件转换为字典# 定义一个列表,存储需要爬取的时间范围
# 您可以根据您的要求修改或添加时间
#time_list = ["202201","202202","202203","202204","202205","202206","202207","202208","202209","202210","202211","202212","202301","202302","202303","202304","202305","202306","202307","202308","202309","202310","202311","202312","202401","202402"]
time_list = ["202301","202302","202303","202304","202305","202306","202307","202308","202309","202310","202311","202312","202401","202402","202403","202404","202405","202406","202407","202408","202409","202410","202411","202412","202501","202502"]# 打开数据库连接
# 您需要提供您的数据库的主机名,用户名,密码,端口号和数据库名
db = pymysql.connect(host="localhost",user="root",passwd="123456",port=3306,db="tianqi")
# 创建一个游标对象
cursor = db.cursor()# 遍历城市字典和时间列表,调用爬取函数
for city, code in city_dict.items():for time in time_list:start = time[:6]end = time[6:]crawl_weather(city, code, start, end, db, cursor)  # 传递 cursor 参数delay.sleep(5)
# 关闭数据库连接
db.close()

数据库设计


http://www.ppmy.cn/server/172914.html

相关文章

认识时钟树

时钟源 高速外部震荡器HSE 低速外部震荡器LSE 高速内部震荡器HSI 低速内部震荡器LSI 易混淆点&#xff1a; RC&#xff08;Resistor-Capacitor&#xff0c;电阻-电容振荡器&#xff09;一般是内部时钟源 RTC&#xff08;Real-Time Clock&#xff0c;实时时钟&#xff09;…

vue下载插件

1.下载路由组件 npm i vue-router2.创建router文件夹 3.创建router.js文件 import {createRouter, createWebHistory} from "vue-router"let router createRouter({history: createWebHistory(),routes: [{path: "/",component: () > import(".…

通过 Groq 后端加载Llama 模型,并调用Function call,也就是通过Groq 后端进行工具的绑定和调用

完整代码&#xff1a; import getpass import os from langchain.chat_models import init_chat_model from langchain_core.tools import tool from langchain_core.messages import HumanMessage, ToolMessage,SystemMessage# 如果没有设置 GROQ_API_KEY&#xff0c;则提示用…

uniapp 解决 H5 跨域问题

使用 uniapp 开发 H5 应用时&#xff0c;若后端没有配置请求域名白名单则接口会出现 CORS 跨域问题&#xff0c;示例如下&#xff1a; Access to XMLHttpRequest at http://www.baidu.cn/api/login from origin http://localhost:5054 has been blocked by CORS policy: Reque…

Java进阶:Zookeeper相关笔记

概要总结&#xff1a; ●Zookeeper是一个开源的分布式协调服务&#xff0c;需要下载并部署在服务器上(使用cmd启动&#xff0c;windows与linux都可用)。 ●zookeeper一般用来实现诸如数据订阅/发布、负载均衡、命名服务、集群管理、分布式锁和分布式队列等功能。 ●有多台服…

std::sort 排序算法本质

使用了内省排序&#xff08;Introsort&#xff09; 现代标准库实现中&#xff0c;std::sort 通常使用 内省排序&#xff08;Introsort&#xff09;&#xff0c;它是一种混合排序算法&#xff0c;结合了以下三种算法的优点&#xff1a; 快速排序 作为主要算法&#xff0c;平均…

CELLO : Causal Evaluation of Large Vision-Language Models

CELLO: Causal Evaluation of Large Vision-Language Models - ACL Anthologyhttps://aclanthology.org/2024.emnlp-main.1247/ 1.概述 因果推理被认为是人类智能的基本组成部分(Penn and Povinelli, 2007;Harari, 2014)。近年来,大型语言模型(LLMs)在视觉语言任务中的成…

【基础4】插入排序

核心思想 插入排序是一种基于元素比较的原地排序算法&#xff0c;其核心思想是将数组分为“已排序”和“未排序”两部分&#xff0c;逐个将未排序元素插入到已排序部分的正确位置。 例如扑克牌在理牌的时候&#xff0c;一般会将大小王、2、A、花牌等按大小顺序插入到左边&…