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

3.7 KiB
Raw Blame History

看到你提供的 HTML 结构了。之所以在公众号后台不显示图片,是因为微信的编辑器有一套非常特殊的图片延迟加载机制

你代码中的图片标签是这样的: <img src="http://..." data-src="http://..." alt="">

问题核心在于:

  1. 协议问题:你的七牛云链接是 http。现在微信后台基本强制要求 https,否则会拦截或显示破损图标。
  2. 关键属性缺失:微信除了 data-src,通常还需要一个 data-type(指定图片格式,如 png/jpeg或者 style 必须包含 width: 100% 以防图片被压成 0 像素。
  3. 双层嵌套限制:你提供的代码里有两个重复的 <div class="rich_media_content"> 容器层级,这可能会导致微信后台解析 CSS 时出错。

解决方案:针对公众号优化的 Python 转换逻辑

我们需要用 BeautifulSoup 来强制修正这些图片标签,并统一把 http 替换为 https

import markdown
import re
from bs4 import BeautifulSoup
from premailer import transform

def fix_wechat_images(html_content):
    soup = BeautifulSoup(html_content, 'html.parser')
    for img in soup.find_all('img'):
        src = img.get('src', '')
        
        # 1. 强制将 http 转换为 https
        if src.startswith('http://'):
            src = src.replace('http://', 'https://')
        
        # 2. 补全微信必须的属性
        img['src'] = src
        img['data-src'] = src
        
        # 3. 强制给图片加行内样式,防止塌陷
        img['style'] = "display: block; margin: 20px auto; width: 100% !important; height: auto !important; visibility: visible !important;"
        
        # 4. 移除可能导致冲突的 class
        if img.get('class'):
            del img['class']
            
    return str(soup)

def md_to_wechat_final(md_text):
    # 基础 Markdown 转换
    html = markdown.markdown(md_text, extensions=['extra', 'fenced_code', 'attr_list'])
    
    # 注入 CSS
    css = """
    <style>
        .rich_media_content { font-size: 16px; line-height: 1.75; color: #333; }
        h1 { font-size: 24px; font-weight: bold; color: #007aff; border-bottom: 2px solid #007aff; padding-bottom: 10px; margin: 1.5em 0 0.5em; }
        h4 { font-size: 16px; font-weight: bold; border-left: 4px solid #007aff; padding-left: 10px; margin: 1em 0; }
        blockquote { background: #f8f9fa; border-left: 4px solid #007aff; padding: 15px; color: #666; }
        pre { background: #2b2b2b; color: #f8f8f2; padding: 15px; border-radius: 6px; overflow-x: auto; }
    </style>
    """
    
    full_html = f'<div class="rich_media_content">{css}{html}</div>'
    
    # 修正图片并转换行内样式
    fixed_html = fix_wechat_images(full_html)
    return transform(fixed_html)

# 使用方式
# final_output = md_to_wechat_final(your_md_content)

操作上的“致命”细节

哪怕代码写对了,操作不对图片也出不来。请务必遵守以下步骤:

  1. 检查七牛云 HTTPS:确保你的七牛云域名已经配置了 SSL 证书。如果 https://img.yidaima.cn/... 在浏览器里打不开,图片永远也进不了公众号。
  2. 不要在编辑器里“粘贴源码”
    • 微信公众号后台没有“查看源码”模式。
    • 你需要用浏览器(推荐 Chrome打开生成的 .html 文件。
    • 在浏览器页面上 Ctrl+A全选 -> Ctrl+C复制
    • 在公众号正文框里直接 Ctrl+V粘贴
  3. 防盗链白名单如果粘贴后显示“此图片来自非官方渠道”你需要去七牛云后台关闭“Referer 防盗链”,或者将 servicewechat.commp.weixin.qq.com 加入白名单。