Use .insert
/.append
method.
import lxml.html
def add_css_code(webpageString, linkString):
root = lxml.html.fromstring(webpageString)
link = lxml.html.fromstring(linkString).find('.//link')
head = root.find('.//head')
title = head.find('title')
if title == None:
where = 0
else:
where = head.index(title) + 1
head.insert(where, link)
return lxml.html.tostring(root)
webpageString1 = "<html><head><title>test</title></head><body>webpage content</body></html>"
webpageString2 = "<html><head></head><body>webpage content</body></html>"
linkString = "<link rel='stylesheet' type='text/css'>"
print(add_css_code(webpageString1, linkString))
print(add_css_code(webpageString2, linkString))