Files
yidaima_tools/docs/md转公众号.md
王鹏 a2f5875d1b init
2026-04-09 14:55:54 +08:00

88 lines
3.3 KiB
Markdown
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

把 Markdown 转化成适合公众号发布的 HTML其实有个“坑”公众号的后台编辑器对 CSS 的支持比较刻薄(很多标准的 CSS 样式会被过滤)。因此,最稳妥的方法是使用**行内样式Inline CSS**。
我们可以使用 Python 的 `markdown` 库配合 `premailer`(用于将 CSS 自动注入到 HTML 标签的 `style` 属性中)来实现。
### 准备工作
你需要安装两个库:
```bash
pip install markdown premailer
```
---
### Python 实现代码
这段代码不仅会转换格式,还会为你预设一套适合阅读的“公众号风”样式:
```python
import markdown
from premailer import transform
def md_to_wechat_html(md_text):
# 1. 定义基本的 CSS 样式(根据公众号审美习惯调整)
css = """
<style>
.rich_media_content { font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif; line-height: 1.6; color: #333; }
h2 { border-bottom: 2px solid #007aff; padding-bottom: 5px; margin-top: 30px; color: #007aff; }
h3 { color: #007aff; margin-top: 20px; }
p { margin: 15px 0; }
blockquote { border-left: 4px solid #ddd; padding-left: 15px; color: #666; font-style: italic; margin: 20px 0; }
code { background-color: #f8f8f8; color: #c7254e; padding: 2px 4px; border-radius: 3px; }
pre { background-color: #282c34; color: #abb2bf; padding: 15px; border-radius: 5px; overflow-x: auto; }
img { max-width: 100%; display: block; margin: 20px auto; }
</style>
"""
# 2. 将 Markdown 转为 HTML启用表格、代码高亮等常用扩展
html_content = markdown.markdown(
md_text,
extensions=['extra', 'codehilite', 'toc']
)
# 3. 组合成完整的 HTML 结构
full_html = f"""
<html>
<body>
<div class="rich_media_content">
{css}
{html_content}
</div>
</body>
</html>
"""
# 4. 使用 premailer 将 CSS 转化为行内样式(公众号最爱的格式)
wechat_friendly_html = transform(full_html)
return wechat_friendly_html
# 测试使用
if __name__ == "__main__":
test_md = """
## 这是一个标题
这是一段正文,包含 **粗体** 和 `行内代码`。
> 这是一个引言块。
### 代码示例
```python
print("Hello WeChat!")
```
"""
result = md_to_wechat_html(test_md)
with open("output.html", "w", encoding="utf-8") as f:
f.write(result)
print("转换成功!请打开 output.html 复制内容到公众号后台。")
```
---
### 避坑小贴士
1. **图片链接**Markdown 里的本地图片链接直接转过去是没用的。你需要先手动上传图片到公众号素材库,或者使用图床,把 MD 里的地址换成 URL。
2. **代码高亮**:公众号对 `pre` 和 `code` 标签的渲染比较特殊。如果上面的代码块样式不够完美,建议考虑使用专门的插件(如 **Markdown Here**)或者将代码块截图上传。
3. **直接粘贴**:运行代码生成的 `output.html` 后,用浏览器打开它,**直接全选复制**,然后粘贴到公众号编辑器里即可,格式基本能保持 90% 以上的一致。
如果你希望样式更精致一点(比如添加特定的配色方案),需要我帮你调整上面的 `css` 变量部分吗?