1、创建一个app.py文件(代码如下)(第三方库:requests\lxml\flask)
2、创建一个templates文件夹,再创建一个index.html
3、敲如下代码
4、运行app.py
5、访问http://127.0.0.1:5000
6、点击查询,可获取到查询结果页面
import requests
from lxml import etree
from flask import Flask, render_template, request
app = Flask(__name__) # 创建一个可以支持web应用的对象
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/112.0.0.0 '
'Safari/537.36'}
resp = requests.get(url, headers=headers)
resp.encoding = 'utf-8'
# 解析数据
e = etree.HTML(resp.text)
# 编写Xpath提取数据
datas_1 = e.xpath('/html/body/div/div[2]/div[2]/div[2]/div[2]/div[2]/table/tbody/tr[1]/td[2]/a[1]/text()')
datas_2 = e.xpath('/html/body/div/div[2]/div[2]/div[2]/div[2]/div[2]/table/tbody/tr[2]/td[2]/span/text()')
datas_3 = e.xpath('/html/body/div/div[2]/div[2]/div[2]/div[2]/div[2]/table/tbody/tr[3]/td[2]/a/text()')
datas = datas_1 + datas_2 + datas_3
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_mobile(phone)
return '<br/>'.join(data)
app.run(debug=True) # 跑服务
<!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.0">
<title>Document</title>
</head>
<body>
<form action="/search_phone" method="get">
手机号:<input type="text" name="phone" id="">
<input type="submit" value="查询">
</form>
</body>
</html>