Flask/Python如何获取HTML中选中的复选框值以执行对应爬取任务
Flask复选框选中状态判断失效解决方法
问题根因
你的判断逻辑本身语法没有错误,生效失败通常是以下两个原因导致:
- 浏览器默认不会提交未选中的复选框参数,
request.args.get(option)对于未选中选项会返回None,但如果你的表单用的是POST提交方式,误用request.args(只能获取GET参数)会导致所有选项都拿不到值,判断永远不成立 - 你在循环内部每次都重新初始化
db = {option: []},会覆盖之前循环存储的选中选项结果,最终仅保留最后一个选中选项的数据,看起来像判断没生效
修复方案
1. 修正HTML表单结构
确认外层form标签的提交方法,这里以GET提交为例,你也可以根据需求换为POST:
<form method="get"> <div><input type="checkbox" name="css">r/css</div> <div><input type="checkbox" name="golang">r/golang</div> <div><input type="checkbox" name="flutter">r/flutter</div> <div><input type="checkbox" name="rust">r/rust</div> <div><input type="checkbox" name="django">r/django</div> <input type="submit" value="Click"> </form>
2. 修正Python后端逻辑
统一适配GET/POST提交,同时调整db初始化位置避免数据覆盖:
from flask import Flask, request, render_template app = Flask(__name__) # 提前定义所有可选选项列表 OPTIONS = ["css", "golang", "flutter", "rust", "django"] @app.route('/crawl', methods=["GET", "POST"]) def crawl(): # 统一获取请求参数,适配GET/POST两种提交方式 req_params = request.args if request.method == "GET" else request.form # 提前初始化存储结果的字典,避免循环内覆盖 crawl_result = {} for option in OPTIONS: # 只要选项存在于请求参数中,就说明用户选中了该选项,不需要硬匹配"on"值 if option in req_params: # 执行爬取逻辑,存入结果字典 data_list = get_list(option) crawl_result[option] = data_list # 后续返回结果的逻辑可根据需求自行调整 return render_template('result.html', data=crawl_result)
内容的提问来源于stack exchange,提问作者Seowoo Jang
相关产品推荐
相关产品推荐

