You need to enable JavaScript to run this app. 如何用Python通过REST API获取WordPress ACF字段的无HTML纯文本内容
优惠活动
大模型
产品
解决方案
定价
更多

如何用Python通过REST API获取WordPress ACF字段的无HTML纯文本内容

处理WordPress REST API返回ACF字段带HTML标签的解决方案

你可以根据可操作权限选择以下任意一种方案解决:

方案1:WordPress服务端配置(源头处理,优先选择)

  • 调整ACF字段类型:如果该字段不需要富文本格式,直接在WordPress后台ACF字段管理页,将对应字段的类型从「富文本编辑器」修改为「文本」或「文本区域(无格式)」,修改后REST API将直接返回无HTML的纯文本内容。
  • 新增REST API返回过滤钩子:如果需要保留后台的富文本编辑能力,仅在API返回时去除HTML,可以在主题的functions.php文件中添加如下代码:
add_filter('acf/rest_api/format_value/type=wysiwyg', function($value, $post_id, $field) {
    return wp_strip_all_tags($value);
}, 10, 3);

配置后所有富文本类型的ACF字段通过REST API返回时都会自动剥离HTML标签。

方案2:Python端处理已拉取的带HTML内容

如果没有权限修改WordPress服务端配置,可以在本地对已获取的内容做标签剥离处理:

  • 无第三方依赖实现:使用Python内置的HTMLParser实现轻量的标签剥离,代码示例如下:
from html.parser import HTMLParser
import html

class MLStripper(HTMLParser):
    def __init__(self):
        super().__init__()
        self.reset()
        self.strict = False
        self.convert_charrefs= True
        self.fed = []
    def handle_data(self, d):
        self.fed.append(d)
    def get_data(self):
        return ''.join(self.fed)

def strip_tags(html_content):
    # 先处理HTML转义字符
    unescaped = html.unescape(html_content)
    s = MLStripper()
    s.feed(unescaped)
    return s.get_data()

# 调用示例
video_content = post_data_dict.get('acf', {}).get('content', '')
pure_text = strip_tags(video_content)
  • 第三方库实现:如果项目允许安装依赖,可以使用BeautifulSoup快速处理,代码更简洁:
    先安装依赖:pip install beautifulsoup4
    调用示例:
from bs4 import BeautifulSoup
import html

video_content = post_data_dict.get('acf', {}).get('content', '')
unescaped = html.unescape(video_content)
pure_text = BeautifulSoup(unescaped, "html.parser").get_text(strip=True)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.04 14:09:01