Use XPath to search for text
The text content extracted from the XML tree is XPath,
>>> Print (html. XPath ("string ()") # lxml. etree only!
Texttail
>>> Print (html. XPath ("// text ()") # lxml. etree only!
['Text', 'tail']
If it is frequently used, you can wrap it into a method:
>>> Build_text_list = etree. XPath ("// text ()") # lxml. etree only!
>>> Print (build_text_list (HTML ))
['Text', 'tail']
You can also use the getparent method to obtain the parent node.
>>> Texts = build_text_list (HTML)
>>> Print (texts [0])
Text
>>> Parent = texts [0]. getparent ()
>>> Print (parent. Tag)
Body
>>> Print (texts [1])
Tail
>>> Print (texts [1]. getparent (). Tag)
BR
You can also find out if it's normal text content or tail text:
>>> Print (texts [0]. is_text)
True
>>> Print (texts [1]. is_text)
False
>>> Print (texts [1]. is_tail)
True
Tree iteration:
Elements provides a tree iterator for iterative access to tree elements.
>>> Root = etree. element ("root ")
>>> Etree. subelement (root, "child"). Text = "CHILD 1"
>>> Etree. subelement (root, "child"). Text = "Child 2"
>>> Etree. subelement (root, "another"). Text = "child 3"
>>> Print (etree. tostring (root, pretty_print = true ))
<Root>
<Child> Child 1 </child>
<Child> Child 2 </child>
<Another> child 3 </Another>
</Root>
>>> For element in root. ITER ():
... Print ("% s-% s" % (element. Tag, element. Text ))
Root-None
Child-Child 1
Child-Child 2
Another-child 3
If you know the tag you are interested in, you can pass the tag name to the ITER Method for filtering.
>>> For element in root. ITER ("child "):
... Print ("% s-% s" % (element. Tag, element. Text ))
Child-Child 1
Child-Child 2
By default, the iterator obtains all nodes of a tree, including instances of processinginstructions, comments and entity. If you want to confirm that only the elements object is returned, you can pass in element factory as a parameter.
>>> Root. append (etree. Entity ("#234 "))
>>> Root. append (etree. Comment ("some comment "))
>>> For element in root. ITER ():
... If isinstance (element. Tag, basestring ):
... Print ("% s-% s" % (element. Tag, element. Text ))
... Else:
... Print ("Special: % s-% s" % (element, element. Text ))
Root-None
Child-Child 1
Child-Child 2
Another-child 3
Special: audio-extract
Special: <! -- Some comment -->-some comment
>>> For element in root. ITER (TAG = etree. element ):
... Print ("% s-% s" % (element. Tag, element. Text ))
Root-None
Child-Child 1
Child-Child 2
Another-child 3
>>> For element in root. ITER (TAG = etree. entity ):
... Print (element. Text)
Bytes