get_mobile_from.py
# 引入框架
import requests
from lxml import etree
from flask import Flask, render_template, request# 创建一个app
app = Flask(__name__)def get_phone_from(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/130.0.0.0 Safari/537.36 Edg/130.0.0.0"}# 发送请求resp = requests.get(url, headers=headers)# 设置字符集 中文显示resp.encoding = "utf-8"# 解析响应# print(resp.text)# 解析数据e = etree.HTML(resp.text)# xpathresult = e.xpath("//tbody//tr//a[1]/text()")return result# 主页
@app.route("/index")
def index():return render_template("/index.html")# 定义路由地址
@app.route("/getPhoneFrom")
def getPhoneFrom():phone = request.args.get("phone")result = get_phone_from(phone)return render_template("index.html", result=result)# 启动web服务
app.run(debug=True)
index.html
<!DOCTYPE html>
<html lang="en"><head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>Document</title>
</head><body><form action="/getPhoneFrom" method="get">手机号:<input type="text" name="phone" id=""><input type="submit" value="查询"></form><table border=""><tr><td>手机号:</td><td>{{result[0]}}</td></tr><tr><td>归属地:</td><td>{{result[1]}}</td></tr><tr><td>运营商:</td><td>{{result[2]}}</td></tr><tr><td>区号:</td><td>{{result[3]}}</td></tr><tr><td>邮编:</td><td>{{result[4]}}</td></tr></table>
</body></html>