Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

lxml, missing doctype when serialized

In [1]: from lxml import etree

I've got an HTML document:

In [2]: root = etree.fromstring(u'''<!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML//EN">\n<HTML></HTML>''', etree.HTMLParser())

Its doctype is parsed correctly:

In [3]: root.getroottree().docinfo.doctype
Out[3]: u'<!DOCTYPE html PUBLIC "-//IETF//DTD HTML//EN">'

But when serializing it, I am losing it:

In [4]: etree.tostring(root.getroottree(), method='html')
Out[4]: '<html></html>'

What should I do to get that doctype serialized?

Debian GNU/Linux, Sid. Python 2.6.6. lxml 2.2.8-2.

like image 969
liori Avatar asked Sep 03 '26 22:09

liori


2 Answers

The only way I've been able to get it to work so far is by using the default XML parser and adding a non-empty system URL to the document:

>>> html = etree.parse(StringIO('''<!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML//EN" " ">\n<HTML></HTML>'''))
>>> etree.tostring(html, method="xml")
'<!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML//EN" " ">\n<HTML/>'
>>> etree.tostring(html, method="html")
'<!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML//EN" " ">\n<HTML></HTML>'

The same thing using the HTMLParser results in the same docinfo, but not the desired output:

>>> html = etree.parse(StringIO('''<!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML//EN" " ">\n<HTML></HTML>'''), etree.HTMLParser())
>>> etree.tostring(html, method="html")
'<html></html>'
like image 72
bosmacs Avatar answered Sep 05 '26 10:09

bosmacs


Bug, as mentioned in a comment to another answer: missing doctype when serialized. Fix in February 2015 to be released in version 3.5 of lxml.

like image 39
liori Avatar answered Sep 05 '26 10:09

liori



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!