本教程仅适用于学习,请勿用于非法用途
本项目使用Python的Flask框架和正则表达式抓取百度实时热搜数据,并通过网页展示。项目包括数据抓取、数据处理和网页渲染三个部分。
环境准备
-
Python环境:确保已安装Python
-
安装依赖库:使用pip安装Flask和requests库
pip install flask requests
项目结构
项目/
├── main.py
└── templates/
└── main.html
代码结构
-
导入库
import requests
import re
import datetime
from flask import Flask, render_template -
初始化Flask应用
app = Flask(__name__)
-
数据抓取函数
def get_hot_search():
url = "https://top.baidu.com/board?tab=realtime"
text = requests.get(url).text
hot_word = re.findall(r'<div class="c-single-text-ellipsis">(.*?) </div>', text)
hot_search = re.findall('<div class="hot-index_1Bl1a">(.*?)</div>', text)
return hot_search, hot_word -
定义路由和视图函数
@app.route("/") # 设置路由,访问根目录时触发
def index():
hot_data = []
num = 0
for i, d in zip(hot_searchs, hot_words):
d = d.replace(" ", "")
if num == 0:
hot_data.append({
"rank": "置顶",
"content": d,
"index": i
})
elif num <= 20:
hot_data.append({
"rank": num,
"content": d,
"index": i
})
num += 1
current_time = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
return render_template("main.html", hot_data=hot_data, current_time=current_time) -
运行应用
if __name__ == '__main__':
hot_searchs, hot_words = get_hot_search()
app.run(host='0.0.0.0', port=9999) -
模板文件 main.html
这个可以自己定义,我这里就用最简单的例子
<html lang="zh">
<head>
<meta charset="UTF-8">
<title>百度实时热搜榜</title>
<style>
/* 表格样式:设置宽度和居中显示 */
table {
width: 80%;
margin: 20px auto;
border-collapse: collapse; /* 合并表格边框 */
}
/* 表格单元格样式 */
th, td {
padding: 10px;
text-align: left;
border: 1px solid #ddd; /* 设置边框 */
}
/* 表头背景色 */
th {
background-color: #f5f5f5;
}
/* 时间显示样式 */
.time {
text-align: center;
color: #666;
margin: 20px;
}
/* 标题样式 */
h1 {
text-align: center;
color: #333;
}
</style>
</head>
<body>
<!-- 页面标题 -->
<h1>百度实时热搜榜</h1>
<!-- 显示更新时间 -->
<p class="time">热搜更新时间:{{ current_time }}</p>
<!-- 热搜数据表格 -->
<table>
<thead>
<tr>
<th>排名</th>
<th>内容</th>
<th>热搜指数</th>
</tr>
</thead>
<tbody>
<!-- 使用Jinja2模板语法遍历热搜数据 -->
{% for item in hot_data %}
<tr>
<td>{{ item.rank }}</td>
<td>{{ item.content }}</td>
<td>{{ item.index }}</td>
</tr>
{% endfor %}
</tbody>
</table>
</body>
</html>
没有回复内容