首页 > 编程语言 >Python爬取7天天气并绘制折线图

Python爬取7天天气并绘制折线图

时间:2022-11-25 12:00:34浏览次数:39  
标签:tem Python list chart 爬取 date weather 折线图 data

Python爬取7天天气

需要的包

  • requests
  • BeautifulSoup
  • openpyxl

安装包

  • 安装命令
pip install [包名]

代码演示

  • 第一部分:爬取文件,写入excel表格
#爬虫获取天气

#导包
import datetime;
import  requests;
from bs4 import BeautifulSoup as bs;
from openpyxl import Workbook;
import re;

#获取网页:101181701为三门峡的代码
url='http://www.weather.com.cn/weather/101181701.shtml';
header={
    #从浏览器找的ua
    'User-Agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/101.0.0.0 Safari/537.36'
}

response=requests.get(url=url,headers=header);
#查看访问情况
print(response.status_code);

#设置文本格式
response.encoding=response.apparent_encoding;
html_doc=response.text;
#测试输出
#print(html_doc);

soup=bs(html_doc,'html.parser');

weather_data_list=soup.find_all('p',class_='tem');
#print(weather_data_list);

#获取今天最高温:最高温有时候会没有,用明天最高温代替
tagToday=soup.find('p',class_="tem")
try:
    temperatureHigh = tagToday.span.string
except   AttributeError  as  e:
    temperatureHigh =\
    tagToday.find_next('p',class_="tem").span.string

print(f"今天最高温度:{temperatureHigh}");

#创建7天日期列表
tem_list=[];
now = datetime.datetime.now();

#取数字正则表达式
reg_digital='\-?\d+\.?\d*'
today_high_temper=re.findall(reg_digital,temperatureHigh);
today_low_temper=re.findall(reg_digital,tagToday.i.string);
#添加今天温度
tem_list.append((now.strftime("%Y-%m-%d"),int(today_high_temper[0]),int(today_low_temper[0])));
print(tem_list);

#日期
date=now;

#添加后面七天的数据,得到七天的数据列表
for weather_data in weather_data_list[1:7]:
    #print(weather_data.i.string);
    date = date + datetime.timedelta(days=1)
    high_digital=re.findall(reg_digital,weather_data.span.string);
    low_digital=re.findall(reg_digital,weather_data.i.string);
    tem_list.append((date.strftime("%Y-%m-%d"),int(high_digital[0]),int(low_digital[0])));

print(tem_list);

#首标题和表头
wb=Workbook();
date_high_low=wb.active;
date_high_low.title=("7天日期统计分析");

date_high_low.append(["日期","最高温","最低温"]);
for row in tem_list:
    date_high_low.append(row);

wb.save("temper.xlsx");
  • 第二部分:读取excel表格,画折线图
#图表可视化
#导包
from openpyxl import load_workbook
from openpyxl.chart import LineChart, Reference;

#加载文件
wb = load_workbook("temper.xlsx");
#加载sheet
ws=wb["7天日期统计分析"];

#日期
date_line=Reference(ws,min_col=1,min_row=2,max_row=8);

#高温低温数据
temper_data=Reference(ws,min_col=2,max_col=3,min_row=2,max_row=8);

chart=LineChart();
chart.title="7天气温统计分析";
chart.x_axis.title="日期";
chart.y_axis.title="温度";

chart.add_data(temper_data);

chart.set_categories(date_line);
chart.legend = None;
line_style = chart.series[0];
line_style.smooth = False;
ws.add_chart(chart, "D2");
wb.save("line.xlsx");

最终效果

  • 效果演示图

标签:tem,Python,list,chart,爬取,date,weather,折线图,data
From: https://www.cnblogs.com/qianshu-homepage/p/16924688.html

相关文章

  • 《python网络爬虫和信息提取》:中国大学排名(附更改前后的代码)
    python网络爬虫和信息提取  《python网络爬虫和信息提取》是北京理工大学的一门网络课程(中国大学MOOC(慕课))。    偶然机会我在网上学习了这门课程,中国大学......
  • Python 基础(一):入门必备知识
    教程源码下载sv20.com目录1标识符2关键字3引号4编码5输入输出6缩进7多行8注释9数据类型10运算符10.1常用运算符10.2运算符优先级基础进阶爬虫自动化数据分析......
  • 【Python】 文件夹压缩 zip
    文件夹压缩zipimportzipfilesrmdir_all_folder#文件夹路径print('原始文件夹路径:',srmdir_all_folder)zip_name='srmdir_all.zip'#压缩文件名称zip_file......
  • Selenium4+Python3系列(八) - Cookie、截图、单选框及复选框处理、富文本框、日历控件操
    我所在的城市昨天出了近20+的阳性案例,但这丝毫没有“影响”到996的工作时间,当然,也没有影响到我想继续更新文章的决心。一、cookie常用操作入门上一篇有写过关于cookie的......
  • Python3基于Centos7的安装
    0x00环境Centos7.9,默认已安装python2.7.50x01依赖软件yuminstallwgetzlib-develbzip2-developenssl-develncurses-develreadline-develtk-develgccmakezl......
  • 第十章python实训
    一、实验目的和要求1、掌握基本文件操作(创建、打开、关闭、写入);2、掌握目录操作的基本操作(创建、删除、遍历);3、了解高级文件操作(删除文件、获取文件基本信息)。二、实验......
  • python中and和or表达式的返回值
    aorb首先明确运算顺序,从左至右#其次只要存在真就会返回真,and返回的是最后一个真,or返回的是第一个真#再次,a,b中存在假,则and返回第一个假,or返回最后一个......
  • 学习《Python编程 从入门到实践》第二、三天
    近期比较忙,宝宝的预产期是12月17日,老婆每天都跟我说准备要生了。所以昨天看了一会就做家务活了,练习完后忘记写日记了。今天给补上。 为什么突然想学编程呢?其实是平常......
  • 在windows系统中搭建python编程环境
    Python环境可以安装在很多不同的系统中,我们python自学网主要考虑到绝大多数学员都是用的是Windows系统,所以就以Windows系统来给大家演示一下python安装的方法,后面也会更新......
  • Python获取当前在线设备ip和mac地址
    获取局域网所在的网段withos.popen("ipconfig/all")asres:forlineinres:line=line.strip()ifline.startswith("IPv4"):i......