from lxml import etree
from copy import deepcopydef prettyprint ( element, ** kwargs) : print ( "/" ) xml = etree. tostring( element, pretty_print= True , ** kwargs) print ( xml. decode( ) , end= '' )
root = etree. Element( "root" )
root. append( etree. Element( "child1" ) )
root. append( etree. Element( "child2" ) )
child3 = etree. SubElement( root, "child3" )
child4 = etree. SubElement( root, "child4" )
child3. append( deepcopy( child4) ) for item in root: print ( item. tag)
print ( list ( root) )
print ( "root.index(root[3]) = %d" % root. index( root[ 3 ] ) )
root. insert( 0 , etree. Element( "child0" ) )
print ( "root[:1] is \t" , root[ : 1 ] )
print ( root[ : 1 ] [ 0 ] . tag)
print ( "root[-1:] is \t" , root[ - 1 : ] )
print ( root[ - 1 : ] [ 0 ] . tag)
if len ( root) : print ( "there are some sub-elements" )
else : print ( "nothing" )
if etree. iselement( root) : print ( "root is element" )
etree. SubElement( root[ 0 ] , "child01" ) if root[ 0 ] [ 0 ] . getparent( ) is root[ 0 ] : print ( "%s's parent is %s" % ( root[ 0 ] [ 0 ] . tag, root[ 0 ] [ 0 ] . getparent( ) . tag) ) if root[ 0 ] is root[ 1 ] . getprevious( ) : print ( "root[0] is root[1].getprevious()" ) if root[ 2 ] is root[ 1 ] . getnext( ) : print ( "root[2] is root[1].getnext()" )
child5 = etree. Element( "a" , href= "https://www.baidu.com" )
root. append( child5)
child5. set ( "class" , "ccdd" )
print ( child5. get( "class" ) )
print ( child5. get( "href" ) )
print ( child5. get( "id" ) )
print ( child5. items( ) )
print ( child5. keys( ) )
print ( child5. values( ) )
print ( child5. attrib) html = etree. Element( "html" )
header = etree. SubElement( html, "header" )
header. text = "this is title"
body = etree. SubElement( html, "body" )
a = etree. SubElement( body, "a" )
a. set ( "href" , "https://csdn.net" )
a. text = "CSDN"
br = etree. SubElement( a, "br" )
br. tail = "end"
print ( etree. tostring( br) )
print ( etree. tostring( br, with_tail= False ) )
print ( etree. tostring( html, method= "text" ) )
print ( root. xpath( "//*[@class='ccdd']" ) )
print ( type ( root. xpath( "//*[@class='ccdd']" ) ) )
print ( len ( root. xpath( "//*[@class='ccdd']" ) ) )
print ( root. xpath( "//*[@class='ccdd']" ) [ 0 ] . tag) for element in root. iter ( ) : print ( f" { element. tag} -- { element. text} " ) print ( "/" ) for element in root. iter ( "child1" , "child2" ) : print ( f" { element. tag} -- { element. text} " ) prettyprint( root)