How to prevent lxml from adding a default doctype <p>lxml seems to add a default doctype when one is missing in the html document.</p> <p>See this demo code:</p> <pre><code>import lxml.etree import lxml.html def beautify(html): parser = lxml.etree.HTMLParser( strip_cdata=True, remove_blank_text=True ) d = lxml.html.fromstring(html, parser=parser) docinfo = d.getroottree().docinfo return lxml.etree.tostring( d, pretty_print=True, doctype=docinfo.doctype, encoding='utf8' ) with_doctype = """ &lt;!DOCTYPE html&gt; &lt;html&gt; &lt;head&gt; &lt;title&gt;With Doctype&lt;/title&gt; &lt;/head&gt; &lt;/html&gt; """ # This passes! assert "DOCTYPE" in beautify(with_doctype) no_doctype = """&lt;html&gt; &lt;head&gt; &lt;title&gt;No Doctype&lt;/title&gt; &lt;/head&gt; &lt;/html&gt;""" # This fails! assert "DOCTYPE" not in beautify(no_doctype) # because the returned html contains this line # &lt;!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" "http://www.w3.org/TR/REC-html40/loose.dtd"&gt; # which was not present in the source before </code></pre> <hr> <p>How can I tell lxml to not do this?</p> <p>This issue was originally raised here: <a href="https://github.com/mitmproxy/mitmproxy/issues/845" rel="nofollow">https://github.com/mitmproxy/mitmproxy/issues/845</a></p> <p>Quoting a <a href="https://www.reddit.com/r/Python/comments/42rb90/comparing_execution_time_of_pretty_printing_an/czclx15" rel="nofollow">comment on reddit</a> as it might be helpful:</p> <blockquote> <p>lxml is based on libxml2, which does this by default unless you pass the option <code>HTML_PARSE_NODEFDTD</code>, I believe. Code <a href="https://github.com/GNOME/libxml2/blob/master/HTMLparser.c#L4777" rel="nofollow">here</a>.</p> <p>I don't know if you can tell lxml to pass that option though.. libxml has python bindings that you could perhaps use directly but they seem really hairy.</p> <p>EDIT: did some more digging and that option does appear in the lxml soure <a href="https://github.com/lxml/lxml/blob/master/src/lxml/includes/htmlparser.pxd#L20" rel="nofollow">here</a>. That option does exactly what you want but I'm not sure how to activate it yet, if it's even possible.</p> </blockquote>