【记录爬虫实战过程】进阶学习·详细过程·爬取天气信息2(python+flask+pyecharts)

5 篇文章 0 订阅
4 篇文章 0 订阅

前言

这个是上一部分的文章传送门:第一部分
接下来开始讲第二部分:flask板块。
关于flask的相关知识我就不详述了,请自行学习

我创建了一个新文件MyFlask.py (注意:不要把名字命名为flask,这样调用时会引起误会)

1. 导入库

from datetime import time
from flask import Flask,render_template,request

#import pandas as pd
import requests  #替代浏览器进行网络请求
import weather #导入之前写好的weather.py文件

2. 写响应函数

2.1. 初始化flask,创建web应用程序

#创建应用程序:web应用程序
app=Flask(__name__)

2.2. 设置路由响应

2.2.1. 进入界面的路由响应
因为一开始我们要打开的界面是一个输入界面,这时 @app.route("/") 对应的响应函数就应该是打开"input.html"

#引入模板->html,flask默认到templates文件夹找html
@app.route("/")  #当访问 http://127.0.0.1:5000/
def input():
    return render_template("input.html")

2.2.2. 进入界面的html文件
按照第一部分提到过的,flask默认在当前项目的templates文件夹里面找文件,所以应该在templates文件夹里面创建"input.html"
在这里插入图片描述
这个界面我们要得到city和year的值,用做之后传入函数的参数

代码如下:

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>查找某城市每年的天气情况</title>
    </head>
    <body id="sousuo" style="text-align: center; padding: 5px;">
        <form action="/search" method="POST">
            <div class="form">
                <p>查找的城市</p>
                <input class="form-name" placeholder="只能输入城市的拼音,如:chengdu" name="city" type="text" autofocus>
            </div><br>
            <div class="form" style="margin-top: 30px;">
                <p>查找的年份</p>
                <input class="form-name" placeholder="只能输入过去的年份,如:2020" name="year" type="text" autofocus>
            </div><br>
            <input type="submit" value="搜索" class="btn" /></br>           
        </form>
    </body>
</html>

2.2.3. 搜索界面的路由响应+主函数main

之前的进入界面代码里面,设置了action会引起"/search" 路由,即这个页面会启动搜索功能
在这里插入图片描述

所以接下来写一个对应的路由响应函数,注意要加上methods!否则页面报错

@app.route("/search",methods=['POST']) 

在这个路由里面,我们要得到“进入界面”输入的city和year的值,传入之前写好的函数里面,最后得到html文件,再展示出来

@app.route("/search",methods=['POST'])  
def show():
    city=request.form.get('city')
    year=request.form.get('year')

    url=weather.getUrl(year,city)    
    weather.creat_html(year,city)
    return render_template("weather.html")

if __name__=='__main__':
    app.run(debug=True) #启动应用程序->启动一个flask项目

设置(debug=True)主要是方便你每次改动代码保存后,网页就会对应进行修改,而不用重启

2.2.4. 进一步改进
现在网页里面输入city的值只支持输入拼音,但是这毕竟不太符合实际,希望把它改成可以输入中文。
上网一查万能的python库果然有办法,这篇单独的文章记了详细步骤,在这里我只简单讲一下代码实现

在MyFlask.py 文件里导入库,用于将拼音转换为中文

""" 将城市的中文转换成拼音 """
from pypinyin import lazy_pinyin

更改响应函数的代码
原代码:

@app.route("/search",methods=['POST'])  
def show():
    city=request.form.get('city')
    year=request.form.get('year')

    time.sleep(1) #设置爬取时间间隔
    url=weather.getUrl(year,city)    
    weather.creat_html(year,city)
    return render_template("weather.html")

改成:

#城市一年天气情况
@app.route("/search",methods=['POST'])  
def show():
    city=request.form.get('city')
    #将城市的中文转换成拼音,便于得到要查找的网站url
    #因为得到的是列表,所以数据要处理一下 如:重庆->['chong', 'qing']
    s = ''
    for i in lazy_pinyin(city):
        s += ''.join(i)
    city=s
    print(city)
    year=request.form.get('year')

    time.sleep(1) #设置爬取时间间隔
    url=weather.getUrl(year,city)    
    weather.creat_html(year,city)
    return render_template("weather.html")

好了,这就是第二部分 MyFlask.py 的全部内容了,这只是一个比较简单例子

完整代码

以下为MyFlask.py 的全部代码:

from datetime import time
from flask import Flask,render_template,request

#import pandas as pd
import requests  #替代浏览器进行网络请求
import weather #导入之前写好的weather.py文件

""" 设置爬取时间间隔 """
import time

""" 将城市的中文转换成拼音 """
# from pypinyin import pinyin
from pypinyin import lazy_pinyin

#创建应用程序:web应用程序
app=Flask(__name__)

#引入模板->html,flask默认到templates文件夹找html
@app.route("/")  #当访问 http://127.0.0.1:5000/
def input():
    #读取CSV文件中的内存,发送到页面即可
    # pd.read_csv("weather.csv")
    return render_template("input.html")

#城市一年天气情况
@app.route("/search",methods=['POST'])  
def show():
    city=request.form.get('city')
    #将城市的中文转换成拼音,便于得到要查找的网站url
    #因为得到的是列表,所以数据要处理一下 如:重庆->['chong', 'qing']
    s = ''
    for i in lazy_pinyin(city):
        s += ''.join(i)
    city=s
    print(city)
    year=request.form.get('year')

    time.sleep(1) #设置爬取时间间隔
    url=weather.getUrl(year,city)    
    weather.creat_html(year,city)
    return render_template("weather.html")

if __name__=='__main__':
    app.run(debug=True) #启动应用程序->启动一个flask项目

之后应该还会对这个项目进行扩展,打算把数据写入MySQL,然后试试用echarts做一些可视化展示。如果做完了还会继续更新

  • 0
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值