Flask开发天气查询软件

作者: 清风Python | 来源:发表于2019-11-21 06:38 被阅读0次
    天气预报

    获取天气预报数据,离不开中国天气网

    天气预报网

    登陆网站,在搜索栏中输入城市名称点击搜索,即可获取该地区的天气预报。比如我搜索西安,完成后会跳转至下面的网址:


    西安天气

    其他的都好说,但是这个地区编码怎么搞?F12看看网络请求....

    爬虫思路
    网络请求
    我们可以看到网站先通过get请求,访问urlhttp://toy1.weather.com.cn/search?cityname=%E8%A5%BF%E5%AE%89并传参cityname,获取到城市编码,再进行了相关跳转。有些young man 会问这个cityname怎么是这种格式...其实很简单:
    from urllib.parse import quote
    quote('西安', encoding='utf-8')
    '%E8%A5%BF%E5%AE%89'
    

    知道了这些,我们就可以有针对性的获取每个城市最近7天的天气预报了,当然少不了一堆beautifulsoup的元素定位操作:


    城市近期天气
    # 元素定位思路:
    id=7d --> class='clearfix' -->ul --> findAll(li)
    # 参数获取
    h1标签为日期
    class=wea 为天气
    class=tem 为温度
    
    爬虫代码

    确定了这些内容,我们的爬虫代码基本就OK了,但这个不是今天的重点,所以简单看下吧:

    # -*- coding: utf-8 -*-
    # @Author   : 王翔
    # @公众号    : 清风Python
    # @Date     : 2019/11/21 05:56
    # @Software : PyCharm
    # @version  :Python 3.7.3
    # @File     : weather.py
    
    
    import requests
    from urllib.parse import quote
    import re
    from bs4 import BeautifulSoup
    
    
    class WeatherReport:
        def __init__(self, city):
            self.quote_city = quote(city, encoding='utf-8')
            self.result_info = []
    
        def get_city_code(self):
            r = requests.get('http://toy1.weather.com.cn/search?cityname=%s' % self.quote_city)
            response = eval(r.text)[0].get('ref')
            try:
                return re.search('[0-9]+', response).group()
            except AttributeError:
                return None
    
        def get_weather(self, code):
            r = requests.get('http://www.weather.com.cn/weather/%s.shtml' % code)
            r.encoding = 'utf-8'
            bs4 = BeautifulSoup(r.text, 'lxml')
            days = bs4.find('div', {'id': '7d'}).find('ul', {"class": "clearfix"}).findAll('li')
            for day in days:
                date = day.h1.text
                weather = day.find('p', {"class": "wea"}).text
                tmp = day.find('p', {"class": 'tem'}).text.strip()
                self.result_info.append("%s: %s %s" %(date,weather, tmp))
            return self.result_info
    
    Web界面

    有了后台的数据,我们前台实现也就比较简单了,只需要提供一个城市的输入框体和提交按钮,剩下就是城市天气的内容展示了。简单引入Bootstrap+jQuery即可完成,前台界面大概这样子,原谅屌丝的审美,哈哈...


    Web界面
    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <meta name="viewport" content="width=device-width, initial-scale=1 ,user-scalable=no">
        <title>清风python</title>
        <link rel="icon" href="{{ url_for('static',filename='favicon.ico') }}">
        <link rel="stylesheet" href="{{ url_for('static',filename='css/bootstrap.min.css') }}">
        <link rel="stylesheet" href="{{ url_for('static',filename='css/main.css') }}">
        <script src="{{ url_for('static',filename='js/jquery.min.js') }}"></script>
    </head>
    <body>
    
    <div class="container container-small">
        <div class="content">
            <div class="header">
                天气查询软件
            </div>
            <div class="block-info">
                <div class="form-group has-success">
                    <div class="input-group">
                        <div class="input-group-addon">
                            城市:
                        </div>
                        <input id='name' class="form-control"/>
    
                    </div>
    
                </div>
                <div class="form-group ">
                    <button class="form-control btn-primary" id="load">查询</button>
                </div>
                <p class="result"></p>
                <script type="text/javascript">
                    $(function () {
                        $('#load').click(function () {
                            let city = $('#name').val();
                            if (city.length > 0) {
                                $.ajax({
                                    url: '/weather/' + city,
                                    type: 'get',
                                    success: function (data) {
                                        $('.result').html(data);
                                    }
                                })
                            } else {
                                $('.result').html("请填写正确的城市名称...");
                            }
                        })
                    })
                </script>
            </div>
        </div>
        <div class="footer">
            ©2019-欢迎关注我的公众号:<a href="https://www.jianshu.com/u/d23fd5012bed">清风Python</a>
        </div>
    </div>
    
    </body>
    </html>
    
    Flask路由

    Flask的路由比较简单,一个用来呈现首页,另外一个负责动态获取Ajax数据进行回传即可

    from flask import Flask, render_template
    from weather import WeatherReport as wr
    
    app = Flask(__name__)
    
    
    @app.route('/')
    def index():
        return render_template('index.html')
    
    
    @app.route('/weather/<city>')
    def weather(city):
        main_func = wr(city)
        city_code = main_func.get_city_code()
        if city_code:
            info = main_func.get_weather(city_code)
            return '<br>'.join(info)
        else:
            return "城市名称无效,请核查..."
    

    !最终实现](https://img.haomeiwen.com/i5847426/2596a980ef4077e3.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)

    pipenv部署

    代码我们已经开发完了,那么如何在手机上部署呢?让我们看看项目目录:


    项目目录

    我将代码提交到github...


    Github

    由于采用pipenv虚拟环境开发,所以使用起来更为方便,只需如下操作:

    # 如果为安装pipenv,需要先进行安装操作
    pip install pipenv
    # 克隆代码
    git clone https://github.com/KingUranus/WeatherForecast.git
    # 进入代码目录
    cd WeatherForecast
    # 安装虚拟机及依赖模块
    pipenv install
    # 进入虚拟机
    pipenv shell
    # 启动flask
    flask run
    
    pipenv导入项目

    最后来看看软件实现吧:


    北京天气

    相关文章

      网友评论

        本文标题:Flask开发天气查询软件

        本文链接:https://www.haomeiwen.com/subject/mkhzictx.html