Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Don't encode Element text object using Python ElementTree

I’m trying to use HTML data inside an the text node of an element, but it gets
encoded as if it were meant to not be HTML data.

Here is an MWE:

from xml.etree import ElementTree as ET

data = '<a href="https://example.com">Example data gained from elsewhere.</a>'

p = ET.Element('p')
p.text = data
p = ET.tostring(p, encoding='utf-8', method='html').decode('utf8')
print(p)

The output is…

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

<p>&lt;a href="https://example.com"&gt;Example data gained from elsewhere.&lt;/a&gt;</p>

What I intended is…

<p><a href="https://example.com">Example data gained from elsewhere.</a></p>

>Solution :

You can parse the HTML string into an ElementTree object and append it to the DOM:

from xml.etree import ElementTree as ET

data = '<a href="https://example.com">Example data gained from elsewhere.</a>'

p = ET.Element('p')
p.append(ET.fromstring(data))
p = ET.tostring(p, encoding='utf-8', method='html').decode('utf8')
print(p)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading