You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Flask项目中display.html无法展示爬虫获取的数据求助

Flask模板无法渲染爬取数据的问题解决

问题现象

爬取的数据已通过print确认存在于列表中,但Flask渲染display.html时,页面表格无法显示任何数据。

问题原因

字典键名大小写不匹配:在scraper.py中,字典的键使用大写开头(如"Name"、"Title"),但在display.html的Jinja2模板中,却以小写键名(如item.name、item.title)访问,导致无法获取对应值。

相关代码对比

scraper.py 数据存储代码

data.append({
    "Name": name,
    "Title": title,
    "Location": location,
    "Experiences": experiences,
    "Education": educations,
    "Certifications": certifications,
    "Skills": skills,
    "Languages": languages
})

app.py 核心逻辑代码

from flask import Flask, render_template, request
import pandas as pd
from scraper import scrape_data

app = Flask(__name__)
app.static_folder = 'static'

@app.route('/upload', methods=['POST'])
def upload():
    file = request.files['file']
    df = pd.read_csv(file)
    data = scrape_data(df)
    return render_template('display.html', data=data)

if __name__ == '__main__':
    app.run(debug=True)

display.html 模板代码

<!DOCTYPE html>
<html>
  <head>
    <meta charset="UTF-8">
    <title>Scraped Information</title>
  </head>
  <body>
    <h1>Scraped Information</h1>
    <table>
      <thead>
        <tr>
          <th>Name</th>
          <th>Title</th>
          <th>Location</th>
          <th>Experiences</th>
          <th>Education</th>
          <th>Certifications</th>
          <th>Skills</th>
          <th>Languages</th>
        </tr>
      </thead>
      <tbody>
        {% for item in data %}
        <tr>
          <td>{{ item.name }}</td>
          <td>{{ item.title }}</td>
          <td>{{ item.location }}</td>
          <td>{{ item.experiences }}</td>
          <td>{{ item.educations }}</td>
          <td>{{ item.certifications }}</td>
          <td>{{ item.skills }}</td>
          <td>{{ item.languages }}</td>
        </tr>
        {% endfor %}
      </tbody>
    </table>
  </body>
</html>

解决方案

任选以下一种方式修改即可:

方式一:修改模板中的键名匹配大写

将display.html里的访问改为对应大写键名:

<tbody>
    {% for item in data %}
    <tr>
        <td>{{ item.Name }}</td>
        <td>{{ item.Title }}</td>
        <td>{{ item.Location }}</td>
        <td>{{ item.Experiences }}</td>
        <td>{{ item.Education }}</td>
        <td>{{ item.Certifications }}</td>
        <td>{{ item.Skills }}</td>
        <td>{{ item.Languages }}</td>
    </tr>
    {% endfor %}
</tbody>

方式二:修改scraper.py中的键名为小写

统一使用小写键名存储数据:

data.append({
    "name": name,
    "title": title,
    "location": location,
    "experiences": experiences,
    "education": educations,
    "certifications": certifications,
    "skills": skills,
    "languages": languages
})

验证建议

修改后重新运行Flask应用,上传文件测试,即可看到表格正常显示数据。

内容的提问来源于stack exchange,提问作者leeteerah

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.23 14:20:25