0

So what I am trying to achieve is really simple.

I want to call python test.py and would like to go to my local host and see the html result. However I keep getting an error ValueError: Invalid tag name u'<html><body><h1>Test!</h1></body></html>'

Below is my code. What's the problem here?

import lxml.etree as ETO
html = ETO.Element("<html><body><h1>Test!</h1></body></html>")
self.wfile.write(ETO.tostring(html, xml_declaration=False, pretty_print=True))
3
  • Are you trying to read an existing file or create a new one? Commented May 8, 2020 at 21:50
  • @JackFleeting I am trying to read existing file! Commented May 9, 2020 at 2:54
  • lxml is not a web server. This looks similar to another question of yours: stackoverflow.com/q/61683853/407651 Commented May 9, 2020 at 4:45

2 Answers 2

0

You have to create each element in turn, and put them in the structure that you want them to have:

html = ETO.Element('html')
body = ETO.SubElement(html, 'body')
h1 = ETO.SubElement(body, 'h1')
h1.text = 'Test!'

Then ETO.tostring(html) will return a bytestring that looks like this:

>>> ETO.tostring(html)
b'<html><body><h1>Test!</h1></body></html>'
Sign up to request clarification or add additional context in comments.

3 Comments

Thank you for your answer! I've dont it before but I realize it's just too much for big files. I want to read the html file within python without creating each element in turn. How do I do that?
If you already have an HTML file, why are you recreating it? I guess I don't understand the problem you're trying to solve.
The python file itself has other functionalities that would be faster in production time if I can just start the server and show my html file in the python code itself. I was wondering if there is any way how to do it.
0

Since you are reading an existing file, Element isn't useful here; try changing this

html = ETO.Element("<html><body><h1>Test!</h1></body></html>")

to this

html = ETO.fromstring("<html><body><h1>Test!</h1></body></html>")

and see if it works for you.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.