1. 程式人生 > 其它 >利用flask+lxml寫簡約project

利用flask+lxml寫簡約project

1.手機歸屬地查詢

效果圖

import requests
from lxml import etree
from flask import Flask,render_template,request

app = Flask(__name__)  

def get_mobile(phone):
    url =f'https://www.ip138.com/mobile.asp?mobile={phone}&action=mobile'



    headers = {
    "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/108.0.0.0 Safari/537.36"
    }


    resp =requests.get(url=url,headers=headers)

    # 設定中文顯示
    resp.encoding='utf-8'

    # print(resp.content)
    # print(resp.text)

    e = etree.HTML(resp.text)

    # infos = e.xpath('//tr/td[2]/span/text()')
    desc = e.xpath('//tbody/tr/td[1]/text()')
    infos = e.xpath('//tr/td[2]/span/text() | //tr/td[2]/a[1]/text()')

    return infos

    # for x,y in zip(desc,infos):
    #
    #     print( f'{x}:{y}')



# a = int(input('請輸入你要查的手機號碼:按q可退出'))

# while True:
#     a = int(input('請輸入你要查的手機號碼:按9可退出查詢:'))
#     if len(str(a)) < 11:
#         print('輸入無效,請輸入有效11位數字')
#     if a == 9:
#         break
#     else:
#         get_mobile(a)

@app.route('/index')
def index():
    return render_template('index.html')  #當前目錄下新建一個template目錄 編寫一個index.html檔案

@app.route('/search_phone') # 建立路由
def search_phone():

    # return 'hello'
    phone = request.args.get('phone')

    data = get_mobile(phone)
    return '<br>'.join(data)


app.run(debug=True)

index.html

<form action="search_phone" method="get">
    手機號:<input type="text" name="phone" id="">
    <input type="submit" value="查詢">
</form>

2.簡約 點贊 記錄

效果圖

from flask import Flask,render_template,request

app = Flask(__name__)

data = [
    {"id":0,"name":"中秋節","num":0},
    {"id":1,"name":"春節","num":0},
    {"id":2,"name":"建軍節","num":0},
]

@app.route('/index')
def findex():
    return render_template('index.html',data=data)

@app.route('/dianzan')
def dianzan():
    id = request.args.get('id')
    print(f'想要給{id}點贊!!!')

    data[int(id)]['num'] += 1
    return render_template('index.html',data=data)



app.run(port=5,debug=True)
<div>
        <h1>這是一個點贊系統</h1>
    </div>

    <table border="1">
        <tr>
        <td>id</td>
        <td>節假日名</td>
        <td>點贊數</td>
        <td>操作</td>
        </tr>
        {% for i in data %}
        <tr>
            <td>{{i.id}}</td>
            <td>{{i.name}}</td>
            <td>{{i.num}}</td>
            <td><a href="/dianzan?id={{ i.id }}">點贊</a></td>
        </tr>
        {% endfor %}
    </table>