Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
575 views
in Technique[技术] by (71.8m points)

html - python lxml append element after another element

I have the following HTML markup

<div id="contents">
    <div id="content_nav">
        something goes here
    </div>
    <p>
        some contents
    </p>   
</div>

To fix some CSS issue, I want to append a div tag <div style="clear:both"></div> after the content_nav div like this

<div id="contents">
    <div id="content_nav">
        something goes here
    </div>

    <div style="clear:both"></div>

    <p>
        some contents
    </p>   
</div>

I am doing it this way:

import lxml.etree

tree = lxml.etree.fromString(inputString, parser=lxml.etree.HTMLParser())

contentnav = tree.find(".//div[@id='content_nav']")
contentnav.append(lxml.etree.XML("<div style='clear: both'></div>"))

But that doesn't append the new div right after content_nav div but inside.

<div id="content_nav">
    something goes here
    <div style="clear:both"></div>
</div>

Is there any way to add a div in the middle of content_nav div and some p like that inside contents?

Thanks

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Instead of appending to contentnav, go up to the parent (contentdiv) and insert the new div at a particular index. To find that index, use contentdiv.index(contentnav), which gives the index of contentnav within contentdiv. Adding one to that gives the desired index.

import lxml.etree as ET

content='''
<div id="contents">
    <div id="content_nav">
        something goes here
    </div>
    <p>
        some contents
    </p>   
</div>
'''
tree = ET.fromstring(content, parser=ET.HTMLParser())
contentnav = tree.find(".//div[@id='content_nav']")
contentdiv = contentnav.getparent()
contentdiv.insert(contentdiv.index(contentnav)+1,
                  ET.XML("<div style='clear: both'></div>"))
print(ET.tostring(tree))

yields

<html><body><div id="contents">
    <div id="content_nav">
        something goes here
    </div>
    <div style="clear: both"/><p>
        some contents
    </p>   
</div></body></html>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

56.9k users

...