整合营销服务商

电脑端+手机端+微信端=数据同步管理

免费咨询热线:

用css绘画动态天气图标

中不同天气的动态图画

废话不多说,直接上源码!喜欢请关注,每天都有分享,谢谢!、

<!DOCTYPE html>

<html>

<head>

<meta charset="utf-8" />

<title>CSS3动画天气图标代码</title>

<link rel="stylesheet" type="text/css" href="css/style.css">

</head>

<body><script src="/demos/googlegg.js"></script>

<div class="icon sun-shower">

<div class="cloud"></div>

<div class="sun">

<div class="rays"></div>

</div>

<div class="rain"></div>

</div>

<div class="icon thunder-storm">

<div class="cloud"></div>

<div class="lightning">

<div class="bolt"></div>

<div class="bolt"></div>

</div>

</div>

<div class="icon cloudy">

<div class="cloud"></div>

<div class="cloud"></div>

</div>

<div class="icon flurries">

<div class="cloud"></div>

<div class="snow">

<div class="flake"></div>

<div class="flake"></div>

</div>

</div>

<div class="icon sunny">

<div class="sun">

<div class="rays"></div>

</div>

</div>

<div class="icon rainy">

<div class="cloud"></div>

<div class="rain"></div>

</div>

<div style="text-align:center;margin:50px 0; font:normal 14px/24px 'MicroSoft YaHei';">

</div>

</body>

</html>

css部分

html { box-sizing: border-box; }

html *,

html *:before,

html *:after { box-sizing: inherit; }

body {

max-width: 42em;

padding: 2em;

margin: 0 auto;

color: #161616;

font-family: 'Roboto', sans-serif;

text-align: center;

background-color: currentColor;

}

所谓数据可视化,我们可以理解为从宏观角度来看一眼就能看出来整个数据的占比,走向。对于数据可视化,很多互联网公司是很看重这一块的,包括大厂;就比如阿里的淘宝,双十一的时候往往就需要将消费者的一些数据通过图的形式展现出来。接下来我们就来实现一个天气的数据可视化(移动端开发),看如下效果图(iPhone6/7/8)。

准备工作

  1. 注册一个高德地图API账号,选择开发支持,地图 JS API。

  1. 登录控制台成为开发者并创建 key。

  1. 进入安全密钥使用说明,找到方式二。

  1. 创建一个vue项目,将vue的一些默认组件和样式删除,在views下新建一个Index.vue,并且在index.js下配置路由。目录结构如下所示:

  1. 通过npm install echarts --save安装一个依赖,这样就可以使用echarts了。

开始(细分11步)

  1. 将准备工作第三步找到的方式二的两个<script>引入到index.html中,将你自己申请的key值和安全密钥粘贴到里面去。这样就可以使用高德地图 JS API 开发地图应用。
  2. 设置头部样式和背景色,时间和切换城市用到了弹性布局。
ini复制代码  //html
  <div class="container">
        <div class="nav">
            <div class="time">7:41</div>
            <div class="city">切换城市</div>
        </div>
  <div>
css复制代码 //css
  .container {
    min-height: 100vh;
    background: #000;
    opacity: 0.7;
    color: #fff;
}

.nav {
    display: flex;
    justify-content: space-between;
    padding: 10px;
}
  1. 设置我们需要的天气数据展示的html+css结构,这主要考查的是切页面能力。
javascript复制代码 //html
 <div class="city-info">
            <p class="city">{{}}</p>
            <p class="weather">{{}}</p>
            <h2 class="temp">
                <em></em>℃
            </h2>
            <div class="detail">
                <span>风力:{{
                }}</span>|
                <span>风向:{{ }}</span>|
                <span>空气湿度:{{  }}</span>
            </div>
        </div>
        <div class="future">
            <div class="group" v-if="futureData.length > 0">
                明天:
                <span class="tm">白天:{{ }}℃ {{ 
                }} {{  }}风 {{ }} </span>
                <span class="tm"> 夜间:{{
                }}℃ {{  }} {{  }}风 {{ 
}}
                </span>
            </div>
            <div class="group" v-if="futureData.length > 0">
                后天:
                <span class="tm">白天:{{ }}℃ {{ 
                }} {{  }}风 {{  }} </span>
                <span class="tm"> 夜间:{{ 
                }}℃ {{  }} {{  }}风 {{ 
}}
                </span>
            </div>
        </div> 
css复制代码//css
.city-info {
    text-align: center;

    .temp {
        font-size: 26px;

        em {
            font-size: 34px;
            font-style: normal;
        }
    }
}

.future {
    padding: 0 10px;
    margin-top: 30px;

    .group {
        height: 44px;
        line-height: 44px;
        background: rgba(255, 255, 255, 0.3);
        margin-bottom: 10px;
        padding: 0 10px;
        font-size: 13px;
        border-radius: 5px;

    }
}

  1. 再放一个div 用于存放折线图。
arduino复制代码//html
<div class="echart-container"> </div>
css复制代码//css
.echart-container {
    width: 100%;
    height: 50vh;
}
  1. 用watchEffect或onMounted来获取天气数据。
  2. 想要获取天气情况我们先要获得定位,这是需要用到高德地图API,我们来到这个位置:开发 > 地图 JS API v2.0 > 教程 > 服务 > 定位,找到IP定位获取当前城市信息。

将这段代码复制到onMounted的回调函数中,这样我们就能获取到定位信息。

  1. 接下来就可以来获取天气了,我们把获取天气封装成一个函数getWeather。同样的我们来到:开发 > 地图 JS API v2.0 > 教程 > 服务 > 天气,找到实时天气查询。

把上图中的代码复制到获取天气的函数中,并将它放在获取定位成功后执行,传入定位的城市,这样就可以获得定位的城市的天气情况了。

  1. 同样的,我们来获取未来几天的天气情况,通过下面的代码就可以获取到。
javascript复制代码weather.getForecast('cityName', function(err, data) {
console.log(err, data); });

注意:此时输出的未来天气是一个数组。

  1. 我们已经获取到了天气数据了,接下来就要把这些数据存起来,把它变成响应式的,然后把它放到页面上展示出来。
ini复制代码 const state = reactive({
            today: {},
            futureData: [],
        })
        
  state.today = data
  state.futureData = data.forecasts
   return {
            ...toRefs(state),
        }

把数据放到页面上我理解的是挖坑然后埋数据,就像下面这样:

ini复制代码 <p class="city">{{ today.city }}</p>
 <p class="weather">{{ today.weather }}</p>

注意:由于futureData是一个数组,我们要在它放数据的div上加一个v-if="futureData.length > 0",要不然会报错。

css复制代码<div class="group" v-if="futureData.length > 0">
                明天:
<span class="tm">白天:{{ futureData[1].dayTemp }}℃ {{ futureData[1].dayWeather}} {{ futureData[1].dayWindDir }}风 {{ futureData[1].dayWindPower }} </span>
<span class="tm"> 夜间:{{ futureData[1].nightTemp }}℃ {{ futureData[1].nightWeather }} {{ futureData[1].nightWindDir }}风 {{ futureData[1].nightWindPower
}}
                </span>
            </div>

  1. 接下来我们就来做一个折线图了,打开ECharts官网,选一个折线图Examples - Apache ECharts

定义一个方法initEchart来完成图的绘制(这里定义了一个空数组来获取未来几天的温度)

kotlin复制代码  const tempArr = ref([])
   data.forecasts.forEach(item => {
                        tempArr.value.push(item.dayTemp)
                    })
  const echartContainer = ref(null)
  const initEchart = () => {
            const myChat = echarts.init(echartContainer.value);
            let option = {
                xAxis: {
                    type: 'category',
                    data: ['今天', '明天', '后天', '大后天'],
                    lineStyle: {
                        color: '#fff'
                    },
                    axisTick: {
                        show: false
                    },

                },
                yAxis: {
                    type: 'value',
                    show: false

                },
                series: [
                    {
                        data: tempArr.value,
                        type: 'line'
                    }
                ]
            };
            myChat.setOption(option)
        }
   return {
            echartContainer
        }

别忘了在装这幅图的div上挂一个ref="echartContainer"哟。

这样就能帮我们初始化一个折线图了。

  1. 最后直接在获取未来天气中调用initEchart就可以了。

部分代码

xml复制代码<script>
import { toRefs, watchEffect, reactive, ref, onMounted } from 'vue';
import * as echarts from 'echarts';


export default {
    setup() {
        const echartContainer = ref(null)
        const state = reactive({
            today: {},
            futureData: [],
        })
        const tempArr = ref([])



        onMounted(() => {
            //1.获取定位
            AMap.plugin('AMap.CitySearch', function () {
                var citySearch = new AMap.CitySearch()
                citySearch.getLocalCity(function (status, result) {
                    // console.log(status);
                    if (status === 'complete' && result.info === 'OK') {
                        // 查询成功,result即为当前所在城市信息
                        //console.log(result.city);
                        getWeather(result.city)
                    }
                })
            })
        })
        const getWeather = (cityName) => {
            //加载天气查询插件
            AMap.plugin('AMap.Weather', function () {
                //创建天气查询实例
                var weather = new AMap.Weather();

                //执行实时天气信息查询
                weather.getLive(cityName, function (err, data) {
                    console.log(err, data);
                    state.today = data
                });
                //未来的天气
                weather.getForecast(cityName, function (err, data) {
                    console.log(err, data);
                    state.futureData = data.forecasts

                    data.forecasts.forEach(item => {
                        tempArr.value.push(item.dayTemp)
                    })
                    initEchart()
                });



            });
        }

        const initEchart = () => {
            const myChat = echarts.init(echartContainer.value);
            let option = {
                xAxis: {
                    type: 'category',
                    data: ['今天', '明天', '后天', '大后天'],
                    lineStyle: {
                        color: '#fff'
                    },
                    axisTick: {
                        show: false
                    },

                },
                yAxis: {
                    type: 'value',
                    show: false

                },
                series: [
                    {
                        data: tempArr.value,
                        type: 'line'
                    }
                ]
            };
            myChat.setOption(option)
        }
        return {
            ...toRefs(state),
            echartContainer
        }
    }
}
</script>

结语

ECharts中的一些图表是很好用的,我们可以自己动手多去尝试尝试。未来的学习之旅还很长,对于数据的可视化我们还可以做成3D的效果。本文如有错失,欢迎大家指正,最后感谢大家的观看,点个免费的赞吧❤️。


作者:一拾九
链接:https://juejin.cn/post/7230078695767294013

次爬取的首页地址是:

http://www.tianqihoubao.com/lishi/nanjing.html

爬取步骤:

  • 爬取主网页,获取进入每个南京市具体年份月份的天气数据的链接
  • 爬取上方获取的具体链接的数据
  • 存储数据
  • 对数据进行筛选后使用pyecharts进行分析

开发工具:

  • Python版本:3.5.4
  • 相关模块:
import requests
from lxml import etree
import time
import csv
from multiprocessing import Pool

使用演示:

  • 部分数据如下:


话不多说,马上开始吧!

  • 步骤一


  • 具体代码如下:
'''
遇到不懂的问题?Python学习交流群:821460695满足你的需求,资料都已经上传群文件,可以自行下载!
'''
def get_mainurl(url): #定义获取月份天气的详细url 函数
 res = requests.get(url, headers=headers)
 main_url = []
 if res.status_code == 200: #判断请求状态
 selector = etree.HTML(res.text)
 htmlurls = selector.xpath('//div[contains(@id,"content")]/div') #循环点
 try:
 for htmlurl in htmlurls:
 Jan = htmlurl.xpath('ul[1]/li[2]/a/@href')[0] #一月份天气url
 main_url.append(Jan) #将网址放入列表中,一个一个放是很蠢的方法,但我也确实不知道其他方法了,下同
 Feb = htmlurl.xpath('ul[1]/li[3]/a/@href')[0] #二月份天气url
 main_url.append(Feb)
 Mar = htmlurl.xpath('ul[1]/li[4]/a/@href')[0] #同上,下类推
 main_url.append(Mar)
 Apr = htmlurl.xpath('ul[2]/li[2]/a/@href')[0]
 main_url.append(Apr)
 May = htmlurl.xpath('ul[2]/li[3]/a/@href')[0]
 main_url.append(May)
 June = htmlurl.xpath('ul[2]/li[4]/a/@href')[0]
 main_url.append(June)
 July = htmlurl.xpath('ul[3]/li[2]/a/@href')[0]
 main_url.append(July)
 Aug = htmlurl.xpath('ul[3]/li[3]/a/@href')[0]
 main_url.append(Aug)
 Sep = htmlurl.xpath('ul[3]/li[4]/a/@href')[0]
 main_url.append(Sep)
 Oct = htmlurl.xpath('ul[4]/li[2]/a/@href')[0]
 main_url.append(Oct)
 Nov = htmlurl.xpath('ul[4]/li[3]/a/@href')[0]
 main_url.append(Nov)
 Dec = htmlurl.xpath('ul[4]/li[4]/a/@href')[0]
 main_url.append(Dec)
​
 time.sleep(0.5) #休眠0.5s
 except IndexError:
 pass
 return main_url #将存了所有url的列表返回
 else:
 pass
​
​
def link_url(url): #上面获取的url是不完整的,此函数使其完整
 final_urls= []
 list_urls = get_mainurl(url)
 for list_url in list_urls:
 if len(list_url) < 30: #因为获取的url有一些少了‘/lishi/’,所以需要判断一下
 list_url = 'http://www.tianqihoubao.com/lishi/' + list_url
 final_urls.append(list_url)
 else:
 list_url = 'http://www.tianqihoubao.com' + list_url
 final_urls.append(list_url)
 return final_urls
  • 步骤二
  • 接下来是获取所需的数据,遍历所在节点就行了,需要注意的是要跳过第一个节点,因为其内部没有内容。

代码如下:

'''
遇到不懂的问题?Python学习交流群:821460695满足你的需求,资料都已经上传群文件,可以自行下载!
'''
def get_infos(detail_url): #爬取月份天气详细数据函数
 main_res = requests.get(detail_url, headers=headers)
 main_sele = etree.HTML(main_res.text)
 main_infos = main_sele.xpath('//div[@class="hd"]/div[1]/table/tr')
 i = True
 try:
 for info in main_infos:
 if i: #此处i的作用是跳过第一次循环,因为第一个是非天气数据
 i = False
 continue
 else:
 date = info.xpath('td[1]/a/text()')[0].replace("\r\n", '').replace(' ', '') #去掉换行符、空格等,下同
 weather = info.xpath('td[2]/text()')[0].replace("\r\n", '').replace(' ', '')
 temps = info.xpath('td[3]/text()')[0].replace('\r\n', '').replace(' ', '')
 clouds = info.xpath('td[4]/text()')[0].replace("\r\n", '').replace(' ', '')
 with open('Nanjing.csv', 'a+', newline='', encoding='utf-8')as fp: #存入csv文件
 writer = csv.writer(fp)
 writer.writerow((date, weather, temps, clouds))
 except IndexError:
 pass
  • 步骤三

接下来执行主程序存储就行了,使用了多进程来爬取加快速度,所以爬取的数据排列可能不按顺序,使用wps或excel自行排序即可。

下方附上剩余代码:

import requests
from lxml import etree
import time
import csv
from multiprocessing import Pool
'''
遇到不懂的问题?Python学习交流群:821460695满足你的需求,资料都已经上传群文件,可以自行下载!
'''
#请求头
headers = {
 'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/73.0.3683.103 Safari/537.36'
}
​
​
​
​
if __name__ == '__main__': #执行主程序
 url = 'http://www.tianqihoubao.com/lishi/nanjing.html' #获取月份天气url的网址
 get_mainurl(url)
 details = link_url(url)
 with open('Nanjing.csv', 'a+', newline='', encoding='utf-8')as ff: #写入第一行作为表头
 writer = csv.writer(ff)
 writer.writerow(('日期', '天气状况', '气温', '风力风向'))
 pool = Pool(processes=4) #使用多进程爬取
 pool.map(get_infos, details) #需要注意爬取结果并不是按顺序的,可以用excel进行排序
  • 步骤四

进行数据分析之前,先用pandas的read_csv()方法将数据读出,然后将2011-2018年的温度和天气状况提取出来进行分析,这里温度需要将数字提取出来,天气状况需要将 ‘/’去掉,还有因为一天的天气数据是多个的(例如一天气温有最高温和最低温),所以后面分析时发现数据量大于8年总天数,这是正常的。

由于我也是第一次使用pyecharts,所以话不多说,直接上代码: