3
\$\begingroup\$

I would like to apply a transformation, say uppercase, to all the text nodes inside a given node. I came up with the following code which works fine for my sample input.

Is there something else that should be considered? I felt that the usage of text vs tail in lxml is a bit asymmetric because text needs to be applied to the main node and tail needs to be applied to the child node.

Can someone review this code?

import lxml.html   

def transform(node):
    if node.text:
        node.text = node.text.upper()
    for child in node.getchildren():
        if child.tail:
            child.tail = child.tail.upper()
        transform(child)

Here is the test case used:

html = """
<html>
   <head>
      <link href="great.css" rel="stylesheet" type="text/css">
      <title>Best Page Ever</title>
   </head>
   <body>
      Body Start
      <div id="1">
         Div 1 Start
         <div id="11">
            Div 11 Start
            Address 1
            <br>
            Address 2
            Div 11 End
         </div>
         <div id="12">
            Div 12 Start
            <div id="121">
              Inside Div 121
            </div>
            Div 12 End
         </div>
         Div 1 End
      </div>
      Body End
   </body>
</html>
"""

root = lxml.html.fromstring(html)

transform(root.get_element_by_id('121'))

print(lxml.html.tostring(root))
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.