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

WP REST API返回HTML+JSON混合内容,Android无法提取纯页面内容求助

解决WordPress REST API返回HTML内容在Android端的处理问题

问题分析

调用WP REST API获取页面内容时,content.rendered字段返回的是包含Elementor页面构建器生成的HTML标签、内联样式的混合内容——这是WordPress默认的渲染逻辑,目的是方便前端直接展示,但在Android端需要额外处理才能提取纯文本或正确显示。

方案1:提取纯文本内容(使用Jsoup库)

Jsoup是Java平台的HTML解析库,可快速去除所有HTML标签,提取纯文本。

  1. 添加依赖
    在Android项目的Module级别build.gradle中引入Jsoup:
dependencies {
    implementation 'org.jsoup:jsoup:1.17.2'
}
  1. 修改代码解析纯文本
    在Volley的onResponse方法中,用Jsoup处理获取到的HTML内容:
String render = mapContent.get("rendered").toString();
// 去除所有HTML标签,提取纯文本
String plainText = Jsoup.parse(render).text();
Log.e("plain_content", plainText);

方案2:直接在WebView中渲染HTML内容

如果需要保留页面的样式和排版,可使用Android WebView直接加载返回的HTML:

  1. 布局中添加WebView
    在对应布局XML文件中加入WebView组件:
<WebView
    android:id="@+id/page_webview"
    android:layout_width="match_parent"
    android:layout_height="match_parent"/>
  1. 修改代码加载HTML
    在onResponse方法中获取HTML并加载到WebView:
String render = mapContent.get("rendered").toString();
WebView webView = findViewById(R.id.page_webview);
// 启用JavaScript(若页面需要交互)
webView.getSettings().setJavaScriptEnabled(true);
// 传入BaseURL确保页面相对资源(如图片)正常加载
webView.loadDataWithBaseURL("https://servicetie.com", render, "text/html", "UTF-8", null);

方案3:在WordPress端过滤API返回内容

若有权限修改WordPress站点,可通过代码过滤API返回的HTML,去除冗余样式和标签:

在WordPress主题的functions.php文件中添加以下代码:

add_filter('rest_prepare_page', 'custom_rest_page_content', 10, 3);
function custom_rest_page_content($response, $post, $request) {
    $content = $response->data['content']['rendered'];
    // 移除Elementor内联样式
    $content = preg_replace('/<style[^>]*>.*?<\/style>/is', '', $content);
    // 移除空的间隔器标签
    $content = preg_replace('/<div class="elementor-spacer[^>]*>.*?<\/div>/is', '', $content);
    // 更新返回内容
    $response->data['content']['rendered'] = $content;
    return $response;
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.30 10:24:53