I am using python 3.3 and lxml 3.2.0
Problem:
I have a web page in a variable webpageString = "<html><head></head><body>webpage content</body></html>"
And I want to insert a css link tag between the two header tags, so that I get
webpageString = "<html><head><link rel='stylesheet' type='text/css'></head><body>webpage content</body></html>"
I have written the following code:
def addCssCode(self):
tree = html.fromstring(self.article)
headTag = tree.xpath("//head")
#htmlTag = tree.getroot()
if headTag is None:
pass #insert the head tag first
cssLinkString = "<link rel='stylesheet' type='text/css' href='"+ self.cssLocation+"'>"
headTag[0].insert(1, html.HtmlElement(cssLinkString))
print(cssLinkString)
self.article = html.tostring(tree).decode("utf-8")
Which results in insertion of-
<HtmlElement>< link rel='stylesheet' type='text/css' href='cssCode.css' ></HtmlElement>
I also tried solution in the following page to an identical problem, but it also didn't work. python lxml append element after another element
How can I solve this? Thanks