在数据采集与展示的开发场景中,我们通常会先通过爬虫获取原始数据,再对数据进行清洗去除无效内容,最后借助Flask框架将数据传递到前端完成展示。整个流程涉及数据清洗、后端接口开发、前端渲染三个核心环节,每个环节的处理方式都会影响最终效果。

数据清洗环节的核心处理
爬虫获取的原始数据往往包含大量无效信息,比如空值、重复内容、格式错误的字段等,需要先完成清洗再传递给Flask。以爬取电商商品数据为例,清洗逻辑通常包含去重、空值填充、格式标准化三个步骤。
以下是使用Python实现数据清洗的示例代码:
import pandas as pd
# 模拟爬虫获取的原始数据
raw_data = [
{"id": 1, "name": "商品A", "price": "100", "stock": None},
{"id": 2, "name": "商品B", "price": "200", "stock": 50},
{"id": 1, "name": "商品A", "price": "100", "stock": None}, # 重复数据
{"id": 3, "name": "商品C", "price": "三百", "stock": 30} # 价格格式错误
]
def clean_spider_data(data):
# 转换为DataFrame方便处理
df = pd.DataFrame(data)
# 去重,根据id字段判断重复
df = df.drop_duplicates(subset=["id"])
# 填充空值,库存为空时默认设为0
df["stock"] = df["stock"].fillna(0)
# 标准化价格字段,将非数字价格转为0
df["price"] = df["price"].apply(lambda x: int(x) if str(x).isdigit() else 0)
# 转换为字典列表返回
return df.to_dict("records")
cleaned_data = clean_spider_data(raw_data)
print(cleaned_data)
Flask后端传递清洗后数据
清洗完成后的数据需要通过Flask的路由传递到前端,常用的传递方式有两种:一种是直接渲染模板时传入数据,另一种是通过接口返回JSON数据供前端异步请求。如果是简单的展示场景,直接渲染模板的方式更高效。
模板渲染方式传递数据
使用Flask的render_template函数,可以将清洗后的数据作为参数传入模板,在前端通过模板语法直接读取。以下是后端路由的实现代码:
from flask import Flask, render_template
app = Flask(__name__)
# 假设已经通过上面的清洗函数得到cleaned_data
cleaned_data = [
{"id": 1, "name": "商品A", "price": 100, "stock": 0},
{"id": 2, "name": "商品B", "price": 200, "stock": 50},
{"id": 3, "name": "商品C", "price": 0, "stock": 30}
]
@app.route("/")
def show_data():
# 将数据传递给index.html模板,变量名为product_list
return render_template("index.html", product_list=cleaned_data)
if __name__ == "__main__":
app.run(debug=True, host="127.0.0.1", port=5000)
JSON接口方式传递数据
如果前端需要通过异步请求获取数据,可以定义返回JSON格式的接口,使用jsonify函数将清洗后的数据转换为JSON响应。实现代码如下:
from flask import Flask, jsonify
app = Flask(__name__)
cleaned_data = [
{"id": 1, "name": "商品A", "price": 100, "stock": 0},
{"id": 2, "name": "商品B", "price": 200, "stock": 50},
{"id": 3, "name": "商品C", "price": 0, "stock": 30}
]
@app.route("/api/products")
def get_products():
# 返回JSON格式数据
return jsonify({"code": 200, "data": cleaned_data, "msg": "success"})
if __name__ == "__main__":
app.run(debug=True, host="127.0.0.1", port=5000)
前端页面展示数据
根据后端传递数据的方式不同,前端展示的实现也有所区别。如果是模板渲染方式,直接在HTML模板中使用Flask的模板语法遍历数据即可;如果是JSON接口方式,则需要通过JavaScript发起请求后渲染数据。
模板渲染方式的前端实现
在templates目录下创建index.html文件,使用{% for %}语法遍历后端传入的product_list数据,以下是完整的前端代码:
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<title>商品数据展示</title>
<style>
table {
border-collapse: collapse;
width: 80%;
margin: 20px auto;
}
th, td {
border: 1px solid #ccc;
padding: 10px;
text-align: center;
}
th {
background-color: #f5f5f5;
}
</style>
</head>
<body>
<h2 style="text-align: center;">清洗后商品数据展示</h2>
<table>
<thead>
<tr>
<th>商品ID</th>
<th>商品名称</th>
<th>价格(元)</th>
<th>库存</th>
</tr>
</thead>
<tbody>
{% for product in product_list %}
<tr>
<td>{{ product.id }}</td>
<td>{{ product.name }}</td>
<td>{{ product.price }}</td>
<td>{{ product.stock }}</td>
</tr>
{% endfor %}
</tbody>
</table>
</body>
</html>
JSON接口方式的前端实现
如果后端提供的是JSON接口,前端可以通过fetch发起请求获取数据后动态渲染页面,代码如下:
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<title>商品数据展示</title>
<style>
table {
border-collapse: collapse;
width: 80%;
margin: 20px auto;
}
th, td {
border: 1px solid #ccc;
padding: 10px;
text-align: center;
}
th {
background-color: #f5f5f5;
}
</style>
</head>
<body>
<h2 style="text-align: center;">清洗后商品数据展示</h2>
<table>
<thead>
<tr>
<th>商品ID</th>
<th>商品名称</th>
<th>价格(元)</th>
<th>库存</th>
</tr>
</thead>
<tbody id="productBody"></tbody>
</table>
<script>
// 发起请求获取JSON数据
fetch("/api/products")
.then(response => response.json())
.then(res => {
if (res.code === 200) {
const tbody = document.getElementById("productBody");
// 遍历数据生成表格行
res.data.forEach(product => {
const tr = document.createElement("tr");
tr.innerHTML = `
<td>${product.id}</td>
<td>${product.name}</td>
<td>${product.price}</td>
<td>${product.stock}</td>
`;
tbody.appendChild(tr);
});
}
});
</script>
</body>
</html>
常见问题与解决方法
- 数据乱码问题:确保爬虫获取数据时指定正确的编码,清洗后传递时统一使用UTF-8编码,前端页面设置
<meta charset="UTF-8">。 - 数据格式错误:清洗数据时统一字段类型,比如价格统一转为数字类型,避免传递混合类型的数据导致前端渲染异常。
- 模板变量未生效:检查
render_template传入的变量名和模板中使用的变量名是否一致,确保模板文件放在templates目录下。