如何使用cms.api向django-cms页面插入原始HTML内容?
Django-CMS 迁移 WordPress 文章:插入原始 HTML 内容解决方案
- 核心逻辑:Django-CMS 的
TextPlugin支持直接传入 HTML 作为body参数,只需正确提取 WordPress 文章的主体 HTML 代码即可完成内容迁移。
具体实现步骤
提取 WordPress 文章主体 HTML
通过 BeautifulSoup 定位文章内容所在的 DOM 容器(WordPress 主题通常会用entry-content或post-content类名包裹文章内容,需根据目标页面实际结构调整选择器),提取容器内的原始 HTML:# 替换为目标页面中文章内容的实际选择器 article_container = soup.find("div", class_="entry-content") # 提取容器内的完整HTML代码 html_content = str(article_container) if article_container else ""将 HTML 内容传入 TextPlugin
修改add_plugin调用,把原示例中的固定文本替换为提取到的 HTML 内容:add_plugin(placeholder, 'TextPlugin', 'en', body=html_content)
完整修改后的代码
import requests as req from cms.api import create_page, add_plugin from bs4 import BeautifulSoup as bs from datetime import datetime raw = req.get("site_base/article/").text soup = bs(raw, "html.parser") # 指定解析器避免警告 title = soup.find("title").text slug = soup.find("meta", {"property":"og:url"})['content'].split("site_base")[1].replace("/","") meta_desc = soup.find("meta", {"name": "description"})['content'] # 提取文章主体HTML(需根据实际页面调整选择器) article_container = soup.find("div", class_="entry-content") html_content = str(article_container) if article_container else "" page = create_page(title, template='home.html', language='en', slug=slug, meta_description=meta_desc, created_by='Sid', publication_date=datetime.now().date()) placeholder = page.placeholders.get(slot='content') add_plugin(placeholder, 'TextPlugin', 'en', body=html_content)
注意事项
- 必须根据目标 WordPress 站点的主题结构调整文章内容的选择器,可通过浏览器开发者工具查看页面 DOM 结构确认。
- 若 HTML 中包含相对路径的图片、内部链接,迁移后需批量替换为 Django-CMS 站点的对应路径,避免资源访问失效。
内容的提问来源于stack exchange,提问作者Sid
相关产品推荐
相关产品推荐

