[英]How to insert a HTML element in a tree of lxml.html
我使用的是python 3.3和lxml 3.2.0
問題:我在變量webpageString = "<html><head></head><body>webpage content</body></html>"
有一個webpageString = "<html><head></head><body>webpage content</body></html>"
,我想在兩個標題之間插入一個css鏈接標記標簽,以便我得到webpageString = "<html><head><link rel='stylesheet' type='text/css'></head><body>webpage content</body></html>"
我寫了以下代碼:
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")
導致插入 -
<HtmlElement>< link rel='stylesheet' type='text/css' href='cssCode.css' ></HtmlElement>
我也嘗試在下一頁解決相同的問題,但它也沒有用。 python lxml追加另一個元素之后的元素
我怎么解決這個問題? 謝謝
使用.insert
/ .append
方法。
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))
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.