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

FastAPI项目中HTML转Wix Ricos格式遇阻,求可行解决方案

解决方案:HTML转Wix Ricos JSON格式(FastAPI场景)

方案1:Python调用Node.js脚本复用Ricos工具

既然你已经尝试过ricos-content的fromRichTextHtml方法,只是项目集成存在问题,可以把转换逻辑封装成独立Node.js脚本,让FastAPI通过子进程调用:

  1. 编写极简Node转换脚本(命名为html-to-ricos.js):
const { fromRichTextHtml } = require('ricos-content');

// 从命令行参数获取HTML内容
const htmlContent = process.argv[2];
if (!htmlContent) {
  console.error('请传入HTML内容');
  process.exit(1);
}

try {
  const ricosJson = fromRichTextHtml(htmlContent);
  console.log(JSON.stringify(ricosJson));
} catch (err) {
  console.error('转换失败:', err);
  process.exit(1);
}
  1. 在FastAPI中调用该脚本(使用Python的subprocess模块):
import subprocess
import json

def html_to_ricos(html: str) -> dict:
    result = subprocess.run(
        ['node', './html-to-ricos.js', html],
        capture_output=True,
        text=True
    )
    if result.returncode != 0:
        raise Exception(f'转换错误: {result.stderr}')
    return json.loads(result.stdout)

# 在FastAPI接口中使用
@app.post("/export-to-wix")
async def export_blog(html_content: str):
    ricos_data = html_to_ricos(html_content)
    # 后续逻辑:发送至Wix API等
    return {"ricos_content": ricos_data}

注意:先在脚本目录执行npm install ricos-content安装依赖;若仍有导入问题,可使用npx直接调用,或用pkg将脚本打包为独立可执行文件。

方案2:自定义轻量转换(适配常见博客内容)

如果你的博客仅包含标题、段落、链接、图片等基础元素,可直接用Python解析HTML并生成Ricos JSON:

from bs4 import BeautifulSoup

def html_to_ricos_custom(html: str) -> dict:
    soup = BeautifulSoup(html, 'html.parser')
    ricos_nodes = []

    for element in soup.descendants:
        if element.name == 'p':
            # 转换段落
            ricos_nodes.append({
                "type": "paragraph",
                "nodes": [{"type": "text", "text": element.get_text(strip=False)}]
            })
        elif element.name in ['h1', 'h2', 'h3']:
            # 转换标题
            level = element.name[1]
            ricos_nodes.append({
                "type": f"heading{level}",
                "nodes": [{"type": "text", "text": element.get_text(strip=False)}]
            })
        elif element.name == 'a':
            # 转换链接
            ricos_nodes.append({
                "type": "paragraph",
                "nodes": [{
                    "type": "text",
                    "text": element.get_text(strip=False),
                    "marks": [{
                        "type": "link",
                        "data": {"url": element.get('href')}
                    }]
                }]
            })
        elif element.name == 'img':
            # 转换图片
            ricos_nodes.append({
                "type": "image",
                "data": {"url": element.get('src'), "alt": element.get('alt', '')}
            })
        # 可扩展列表、粗体、斜体等元素的转换逻辑

    # 组装Ricos完整结构
    return {"document": {"nodes": ricos_nodes}}

该方案无需依赖外部工具,可控性强,可根据自身博客内容灵活扩展。

方案3:通用工具中转适配

先将HTML转成Markdown,再通过Markdown转Ricos工具完成转换:

  • 用Python的markdownify库将HTML转为Markdown
  • 借助ricos-markdown等工具,通过Python调用Node脚本的方式完成Markdown到Ricos JSON的转换

此方式适合HTML结构复杂但Markdown可覆盖的场景,通过中转降低转换复杂度。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.14 11:28:18