使用docutils HTML5 writer时,fragment仍含docinfo是操作问题还是Bug?
Docutils HTML5 Writer: Docinfo Appearing in
fragment Part 我之前也碰到过这个让人头疼的问题,咱们一步步来理清这到底是操作失误还是writer的bug:
首先确认是不是自身操作问题
先检查你有没有在初始化HTML5 Writer时设置了特殊的配置项,导致docinfo被意外包含进了fragment。你可以用这段最小复现代码验证:
from docutils.core import publish_string from docutils.writers.html5_polyglot import Writer as HTML5Writer from docutils.writers.html4css1 import Writer as HTMLWriter # 带docinfo字段的测试RST内容 test_rst = """ :Author: Jane Smith :Version: 1.0 This is the main content of the document. """ # 测试HTML5 Writer html5_result = publish_string(test_rst, writer=HTML5Writer()) has_docinfo_html5 = '<dl class="docinfo simple">' in html5_result.writer.parts['fragment'] print(f"HTML5 fragment has docinfo: {has_docinfo_html5}") # 按文档应返回False,但实际可能是True # 对比标准HTML Writer html_result = publish_string(test_rst, writer=HTMLWriter()) has_docinfo_html = '<dl class="docinfo simple">' in html_result.writer.parts['fragment'] print(f"Standard HTML fragment has docinfo: {has_docinfo_html}") # 正常返回False
如果运行后HTML5的fragment确实包含docinfo,那基本可以排除是你的操作问题——你完全遵循了官方文档中fragment应仅包含主体内容的描述,且标准HTML Writer的行为符合预期。
这很可能是HTML5 Writer的Bug
Docutils官方文档明确说明fragment部分是不包含docinfo、页眉、页脚等外围元素的文档主体内容。HTML5 Writer和标准HTML Writer的行为不一致,这大概率是实现上的疏漏。
你可以去Docutils的官方issue追踪平台搜一下有没有类似的报告,如果没有的话,提交一个包含复现代码的issue会很有帮助,开发者们会关注到这个不一致的问题。
临时解决办法
如果需要快速解决这个问题,可以用HTML解析库(比如BeautifulSoup)手动移除fragment中的docinfo元素:
from bs4 import BeautifulSoup # 从HTML5 Writer获取fragment raw_fragment = html5_result.writer.parts['fragment'] # 解析并移除docinfo soup = BeautifulSoup(raw_fragment, 'html.parser') docinfo_element = soup.find('dl', class_='docinfo simple') if docinfo_element: docinfo_element.decompose() # 得到清理后的fragment clean_fragment = str(soup)
内容的提问来源于stack exchange,提问作者Cédric Van Rompay
相关产品推荐
相关产品推荐

