
本文讲解如何正确使用 html.escape() 函数将商品标题与颜色字符串安全拼接(如 "title (red, blue, green)"),避免因误调用导致 'str' object is not callable 错误,并确保输出内容可安全用于 html 环境。
本文讲解如何正确使用 html.escape() 函数将商品标题与颜色字符串安全拼接(如 "title (red, blue, green)"),避免因误调用导致 'str' object is not callable 错误,并确保输出内容可安全用于 html 环境。
你在代码中遇到的错误:
"Title": escape((title)(coloror))
根本原因在于:你把字符串 title 和 coloror 当作函数调用了(即 (title)(coloror) 语法),而 Python 将其解释为“尝试以 coloror 为参数调用 title 这个字符串对象”——但字符串不可调用,因此抛出 TypeError: 'str' object is not callable。
此外,escape() 并非内置函数,它来自标准库 html 模块,必须显式导入,否则会触发 NameError。
✅ 正确做法如下:
立即学习“Python免费学习笔记(深入)”;
1. 正确导入与使用 html.escape
import html
# 假设 title = "Summer Dress"
# coloror = "Red, Blue, Green"
full_title = f"{title} ({coloror})"
safe_title = html.escape(full_title) # ✅ 安全转义 HTML 特殊字符
item = {
"Item": {
"Title": safe_title
}
}2. 完整修复后的关键代码段(含健壮性处理)
import html
print('Title: ', title)
color_list = []
# 遍历 product_data 提取所有颜色(注意:确保 data['color'] 是字符串或可转为字符串)
for data in product_data:
color = data.get('color', '')
if isinstance(color, list):
color_list.extend(color) # 支持 color 字段为列表(如 ["Red", "Black"])
else:
color_list.append(str(color))
# 去重 + 过滤空值,再拼接
clean_colors = [c.strip() for c in color_list if c and str(c).strip()]
coloror = ', '.join(clean_colors) if clean_colors else ''
# 构建并转义最终标题
full_title = title.strip()
if coloror:
full_title += f" ({coloror})"
safe_title = html.escape(full_title)
item = {
"Item": {
"Title": safe_title
}
}⚠️ 注意事项:
- 永远不要省略 import html —— html.escape() 不是内置函数;
- 拼接用 + 或 f-string,不是括号调用:(title)(coloror) ❌ → f"{title} ({coloror})" ✅;
- html.escape() 仅对 <, >, &, ", ' 等字符做转义,适合嵌入 HTML;若用于 JSON/API 返回,通常无需转义(除非明确输出到 HTML 上下文);
- 若 product_data 中 color 字段可能为空、None 或嵌套结构,请务必加 get() 和类型判断,避免运行时异常。
✅ 总结
修复核心三步:
① import html;
② 用字符串拼接(非函数调用)构造完整标题;
③ 对最终字符串调用 html.escape() 得到安全 HTML 内容。
这样既消除了 TypeError,又防范了 XSS 风险,符合电商系统对商品元数据的安全要求。


















