前言:
利用python的flask框架制作简单的手机号码归属地查询工具。首先需要做两个页面,第一个页面收集用户的输入信息,点击“查询”按钮后,跳转到第二个页面,显示查询到的信息。
一、flask框架的使用套路:
from flask import Flask, render_template
from flask import request
app = Flask(__name__)
@app.route('/')
def index():
return render_template('index.html')
@app.route('/search_phone')
def search_phone():
phone = request.args.get('phone')
data = get_data(phone)
return '<br/>'.join(data)
# get_data(13914879121)
app.run(debug=True)
二、完整实例:
import requests
from lxml import etree
from flask import Flask, render_template
from flask import request
app = Flask(__name__)
def get_data(phone):
url = f"https://www.ip138.com/mobile.asp?mobile={phone}&action=mobile"
headers = {
"User-Agent": "Mozilla/5.0(Windows NT 6.1;WOW64) AppleWebKit/537.36(KABUL, like Gecko) "
"Chrome/86.0.4240.198Safari/537.36 "
}
resp = requests.get(url, headers=headers)
resp.encoding = resp.apparent_encoding
e = etree.HTML(resp.text)
datas = e.xpath('//tr/td[2]/span/text()')
return datas
@app.route('/')
def index():
return render_template('index.html')
@app.route('/search_phone')
def search_phone():
phone = request.args.get('phone')
data = get_data(phone)
return '<br/>'.join(data)
# get_data(13914879121)
app.run(debug=True)