python爬取天气数据的实例详解


Posted in Python onNovember 20, 2020

就在前几天还是二十多度的舒适温度,今天一下子就变成了个位数,小编已经感受到冬天寒风的无情了。之前对获取天气都是数据上的搜集,做成了一个数据表后,对温度变化的感知并不直观。那么,我们能不能用python中的方法做一个天气数据分析的图形,帮助我们更直接的看出天气变化呢?

使用pygal绘图,使用该模块前需先安装pip install pygal,然后导入import pygal

bar = pygal.Line() # 创建折线图
bar.add('最低气温', lows)  #添加两线的数据序列
bar.add('最高气温', highs) #注意lows和highs是int型的列表
bar.x_labels = daytimes
bar.x_labels_major = daytimes[::30]
bar.x_label_rotation = 45
bar.title = cityname+'未来七天气温走向图'  #设置图形标题
bar.x_title = '日期'  #x轴标题
bar.y_title = '气温(摄氏度)' # y轴标题
bar.legend_at_bottom = True
bar.show_x_guides = False
bar.show_y_guides = True
bar.render_to_file('temperate1.svg') # 将图像保存为SVG文件,可通过浏览器

最终生成的图形如下图所示,直观的显示了天气情况:

python爬取天气数据的实例详解

完整代码

import csv
import sys
import urllib.request
from bs4 import BeautifulSoup # 解析页面模块
import pygal
import cityinfo
 
cityname = input("请输入你想要查询天气的城市:")
if cityname in cityinfo.city:
  citycode = cityinfo.city[cityname]
else:
  sys.exit()
url = '非常抱歉,网页无法访问' + citycode + '.shtml'
header = ("User-Agent","Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/76.0.3809.132 Safari/537.36") # 设置头部信息
http_handler = urllib.request.HTTPHandler()
opener = urllib.request.build_opener(http_handler) # 修改头部信息
opener.addheaders = [header]
request = urllib.request.Request(url) # 制作请求
response = opener.open(request) # 得到应答包
html = response.read() # 读取应答包
html = html.decode('utf-8') # 设置编码,否则会乱码
# 根据得到的页面信息进行初步筛选过滤
final = [] # 初始化一个列表保存数据
bs = BeautifulSoup(html, "html.parser") # 创建BeautifulSoup对象
body = bs.body
data = body.find('div', {'id': '7d'})
print(type(data))
ul = data.find('ul')
li = ul.find_all('li')
# 爬取自己需要的数据
i = 0 # 控制爬取的天数
lows = [] # 保存低温
highs = [] # 保存高温
daytimes = [] # 保存日期
weathers = [] # 保存天气
for day in li: # 便利找到的每一个li
  if i < 7:
    temp = [] # 临时存放每天的数据
    date = day.find('h1').string # 得到日期
    #print(date)
    temp.append(date)
    daytimes.append(date)
    inf = day.find_all('p') # 遍历li下面的p标签 有多个p需要使用find_all 而不是find
    #print(inf[0].string) # 提取第一个p标签的值,即天气
    temp.append(inf[0].string)
    weathers.append(inf[0].string)
    temlow = inf[1].find('i').string # 最低气温
    if inf[1].find('span') is None: # 天气预报可能没有最高气温
      temhigh = None
      temperate = temlow
    else:
      temhigh = inf[1].find('span').string # 最高气温
      temhigh = temhigh.replace('℃', '')
      temperate = temhigh + '/' + temlow
    # temp.append(temhigh)
    # temp.append(temlow)
    lowStr = ""
    lowStr = lowStr.join(temlow.string)
    lows.append(int(lowStr[:-1])) # 以上三行将低温NavigableString转成int类型并存入低温列表
    if temhigh is None:
      highs.append(int(lowStr[:-1]))
      highStr = ""
      highStr = highStr.join(temhigh)
      highs.append(int(highStr)) # 以上三行将高温NavigableString转成int类型并存入高温列表
    temp.append(temperate)
    final.append(temp)
    i = i + 1
# 将最终的获取的天气写入csv文件
with open('weather.csv', 'a', errors='ignore', newline='') as f:
  f_csv = csv.writer(f)
  f_csv.writerows([cityname])
  f_csv.writerows(final)
# 绘图
bar = pygal.Line() # 创建折线图
bar.add('最低气温', lows)
bar.add('最高气温', highs)
bar.x_labels = daytimes
bar.x_labels_major = daytimes[::30]
# bar.show_minor_x_labels = False # 不显示X轴最小刻度
bar.x_label_rotation = 45
bar.title = cityname+'未来七天气温走向图'
bar.x_title = '日期'
bar.y_title = '气温(摄氏度)'
bar.legend_at_bottom = True
bar.show_x_guides = False
bar.show_y_guides = True
bar.render_to_file('temperate.svg')

Python爬取天气数据实例扩展:

import requests
from bs4 import BeautifulSoup
from pyecharts import Bar

ALL_DATA = []
def send_parse_urls(start_urls):
  headers = {
  "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/81.0.4044.122 Safari/537.36"
  }
  for start_url in start_urls:
    response = requests.get(start_url,headers=headers)
    # 编码问题的解决
    response = response.text.encode("raw_unicode_escape").decode("utf-8")
    soup = BeautifulSoup(response,"html5lib") #lxml解析器:性能比较好,html5lib:适合页面结构比较混乱的
    div_tatall = soup.find("div",class_="conMidtab") #find() 找符合要求的第一个元素
    tables = div_tatall.find_all("table") #find_all() 找到符合要求的所有元素的列表
    for table in tables:
      trs = table.find_all("tr")
      info_trs = trs[2:]
      for index,info_tr in enumerate(info_trs): # 枚举函数,可以获得索引
        # print(index,info_tr)
        # print("="*30)
        city_td = info_tr.find_all("td")[0]
        temp_td = info_tr.find_all("td")[6]
        # if的判断的index的特殊情况应该在一般情况的后面,把之前的数据覆盖
        if index==0:
          city_td = info_tr.find_all("td")[1]
          temp_td = info_tr.find_all("td")[7]
        city=list(city_td.stripped_strings)[0]
        temp=list(temp_td.stripped_strings)[0]
        ALL_DATA.append({"city":city,"temp":temp})
  return ALL_DATA

def get_start_urls():
  start_urls = [
    "http://www.weather.com.cn/textFC/hb.shtml",
    "http://www.weather.com.cn/textFC/db.shtml",
    "http://www.weather.com.cn/textFC/hd.shtml",
    "http://www.weather.com.cn/textFC/hz.shtml",
    "http://www.weather.com.cn/textFC/hn.shtml",
    "http://www.weather.com.cn/textFC/xb.shtml",
    "http://www.weather.com.cn/textFC/xn.shtml",
    "http://www.weather.com.cn/textFC/gat.shtml",
  ]
  return start_urls

def main():
  """
  主程序逻辑
  展示全国实时温度最低的十个城市气温排行榜的柱状图
  """
  # 1 获取所有起始url
  start_urls = get_start_urls()
  # 2 发送请求获取响应、解析页面
  data = send_parse_urls(start_urls)
  # print(data)
  # 4 数据可视化
    #1排序
  data.sort(key=lambda data:int(data["temp"]))
    #2切片,选择出温度最低的十个城市和温度值
  show_data = data[:10]
    #3分出城市和温度
  city = list(map(lambda data:data["city"],show_data))
  temp = list(map(lambda data:int(data["temp"]),show_data))
    #4创建柱状图、生成目标图
  chart = Bar("中国最低气温排行榜") #需要安装pyechart模块
  chart.add("",city,temp)
  chart.render("tempture.html")

if __name__ == '__main__':
  main()

到此这篇关于python爬取天气数据的实例详解的文章就介绍到这了,更多相关python爬虫天气数据的分析内容请搜索三水点靠木以前的文章或继续浏览下面的相关文章希望大家以后多多支持三水点靠木!

Python 相关文章推荐
Python学习笔记整理3之输入输出、python eval函数
Dec 14 Python
python 获取当天每个准点时间戳的实例
May 22 Python
python xpath获取页面注释的方法
Jan 14 Python
Python微信操控itchat的方法
May 31 Python
Python中sorted()排序与字母大小写的问题
Jan 14 Python
python 工具 字符串转numpy浮点数组的实现
Mar 14 Python
Django如何批量创建Model
Sep 01 Python
Python 操作 MySQL数据库
Sep 18 Python
python 制作简单的音乐播放器
Nov 25 Python
用Python实现童年贪吃蛇小游戏功能的实例代码
Dec 07 Python
彻底解决pip下载pytorch慢的问题方法
Mar 01 Python
深入理解pytorch库的dockerfile
Jun 10 Python
python爬取招聘要求等信息实例
Nov 20 #Python
python爬虫判断招聘信息是否存在的实例代码
Nov 20 #Python
Python getsizeof()和getsize()区分详解
Nov 20 #Python
Python析构函数__del__定义原理解析
Nov 20 #Python
Python request post上传文件常见要点
Nov 20 #Python
接口自动化多层嵌套json数据处理代码实例
Nov 20 #Python
如何设置PyCharm中的Python代码模版(推荐)
Nov 20 #Python
You might like
将PHP作为Shell脚本语言使用
2006/10/09 PHP
ajax返回值中有回车换行、空格的解决方法分享
2013/10/24 PHP
完美利用Yii2微信后台开发的系列总结
2016/07/18 PHP
破除一些网站复制、右键限制
2006/11/04 Javascript
Js的MessageBox
2006/12/03 Javascript
javascript实现页面内关键词高亮显示代码
2014/04/03 Javascript
让javascript加载速度倍增的方法(解决JS加载速度慢的问题)
2014/12/12 Javascript
DOM基础教程之使用DOM设置文本框
2015/01/20 Javascript
JS动态修改iframe高度和宽度的方法
2015/04/01 Javascript
JavaScript实现为指定对象添加多个事件处理程序的方法
2015/04/17 Javascript
javascript元素动态创建实现方法
2015/05/13 Javascript
jQuery使用经验小技巧(推荐)
2016/05/31 Javascript
解决微信浏览器Javascript无法使用window.location.reload()刷新页面
2016/06/21 Javascript
angular分页指令操作
2017/01/09 Javascript
浅谈angularjs $http提交数据探索
2017/01/20 Javascript
jQuery模拟爆炸倒计时功能实例代码
2017/08/21 jQuery
使用jQuery实现简单的tab框实例
2017/08/22 jQuery
Node.js 使用流实现读写同步边读边写功能
2017/09/11 Javascript
基于vue打包后字体和图片资源失效问题的解决方法
2018/03/06 Javascript
Python下载指定页面上图片的方法
2016/05/12 Python
简单谈谈Python中的反转字符串问题
2016/10/24 Python
利用Python中的pandas库对cdn日志进行分析详解
2017/03/07 Python
Django使用Mysql数据库已经存在的数据表方法
2018/05/27 Python
Python参数类型以及常见的坑详解
2019/07/08 Python
python字符串判断密码强弱
2020/03/18 Python
美国家庭鞋店:Shoe Sensation
2019/09/27 全球购物
PHP面试题附答案
2015/11/28 面试题
销售简历自我评价
2014/01/24 职场文书
迟到检讨书5000字
2014/01/31 职场文书
同事吵架检讨书
2014/02/05 职场文书
2014新课程改革心得体会
2014/03/10 职场文书
大四毕业生自荐书
2014/07/05 职场文书
党员自我评议个人对照检查材料
2014/09/16 职场文书
奠基仪式致辞
2015/07/30 职场文书
2015年大学组织委员个人工作总结
2015/10/23 职场文书
银行客户经理培训心得体会
2016/01/09 职场文书