返回 Social Auto Upload
content.py
1 """将原稿转换为雪球实测可接收的结构,图片仍保留原位置和本地路径。"""
2 from html import escape
3 from html.parser import HTMLParser
4
5 from utils.article_content import ArticleDocument
6 from utils.article_render import ARTICLE_MARKDOWN_EXTENSIONS, load_article
7
8
9 class XueqiuHTML(HTMLParser):
10 """平台会过滤 CSS、统一标题并展开列表;导入前保留可见列表编号。"""
11
12 def __init__(self):
13 super().__init__(convert_charrefs=True)
14 self.parts = []
15 self.lists = []
16 self.changes = set()
17
18 def handle_starttag(self, tag, attrs):
19 """仅转换已有安全解析器接受的结构;未知格式明确报错,不悄悄丢内容。"""
20 attrs = dict(attrs)
21 if tag not in {"section", "div", "p", "br", "span", "strong", "b", "em", "i", "a", "img",
22 "h1", "h2", "h3", "h4", "h5", "h6", "ul", "ol", "li", "blockquote", "figure", "figcaption"}:
23 raise ValueError(f"雪球原生编辑器尚未验证 <{tag}>,请转换为段落或本地图片后上传")
24 if attrs.get("style"):
25 self.changes.add("自定义样式使用雪球原生样式")
26 if tag.startswith("h") and len(tag) == 2:
27 if tag != "h4":
28 self.changes.add("各级标题统一为雪球小标题")
29 tag = "h4"
30 elif tag in {"ul", "ol"}:
31 self.changes.add("列表转换为带序号或圆点的段落")
32 self.lists.append([tag, int(attrs.get("start", "1"))])
33 tag = "div"
34 elif tag == "li":
35 if not self.lists:
36 raise ValueError("列表项必须位于 ul 或 ol 中")
37 kind, number = self.lists[-1]
38 self.lists[-1][1] += 1
39 self.parts.append(f'<div>{number}. ' if kind == "ol" else '<div>• ')
40 return
41 elif tag == "blockquote":
42 self.changes.add("引用保留文字和段落,使用雪球原生段落样式")
43 tag = "div"
44 elif tag in {"section", "figure", "figcaption"}:
45 tag = "div"
46 # 原稿已通过 ArticleDocument 校验;不把 CSS/class 导入编辑器,避免样式保留的假象。
47 keep = {key: value for key, value in attrs.items()
48 if (tag == "a" and key == "href") or (tag == "img" and key in {"src", "alt"})}
49 self.parts.append("<" + tag + "".join(f' {key}="{escape(value or "", quote=True)}"'
50 for key, value in keep.items()) + ">")
51
52 def handle_endtag(self, tag):
53 """结束标签与开始标签使用同一转换,避免生成失配的富文本。"""
54 if tag in {"ul", "ol"}:
55 self.lists.pop()
56 if tag in {"section", "figure", "figcaption", "ul", "ol", "li", "blockquote"}:
57 tag = "div"
58 elif tag.startswith("h") and len(tag) == 2:
59 tag = "h4"
60 self.parts.append(f"</{tag}>")
61
62 def handle_data(self, value):
63 """保留原始文字和空白,特殊字符按 HTML 文本转义。"""
64 self.parts.append(escape(value))
65
66
67 def load_xueqiu_article(path):
68 """复用仓库的 HTML/Markdown/TXT 输入与相对图片路径,返回待核对的转换后正文。"""
69 original = load_article(path, "plain" if path.suffix.lower() in ARTICLE_MARKDOWN_EXTENSIONS else None)
70 converted = XueqiuHTML()
71 converted.feed(original.content_html)
72 converted.close()
73 document = ArticleDocument("".join(converted.parts), path.parent)
74 document.source_format = original.source_format
75 document.normalizations = sorted(converted.changes)
76 return document
77
77 lines PYTHON