2013-06-21 37 views
1

我使用python 3.3和3.2.0 LXML如何lxml.html樹

問題插入一個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") 

WHI ch結果插入 -

<HtmlElement>&lt; link rel='stylesheet' type='text/css' href='cssCode.css' &gt;</HtmlElement> 

我也在下面的頁面中嘗試瞭解決方案,以解決相同的問題,但它也沒有奏效。 python lxml append element after another element

我該如何解決這個問題? 謝謝

回答

0

使用.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)) 
+0

感謝它的工作,但它與append()方法沒有任何關係。我必須使用insert(),因爲我需要在特定位置插入鏈接標籤,即在標題標籤之後。 – user1986258

+0

@ user1986258,我更新了代碼。 – falsetru